1

I'm using the CSS typings from csstype to set CSS style objects. However, I'd like to allow a CSS property to be null.

From what I understand, this should work:

import * as CSS from "csstype";

type CSSProperties = CSS.Properties<number | string>;

type CSSObject = CSSProperties & { [K in keyof CSSProperties]: CSSProperties[K] | null };

let k: CSSObject = {
  background: null
};

However, I get an error that Type 'null' is not assignable to type 'string | number | undefined'.. I essentially want CSSObject to have all the same keys as CSS.Properties, but with each key also allowing a null value.

2 Answers 2

4

There's no reason to & the whole object with the "or null" part on the right (talking about your third line). I don't have 'csstype' at hand, so here's a quick demo with a random custom interface.

type OrNull<T> = { [K in keyof T]: T[K] | null }

interface Interface {
    a: number
    b: string
}

type InterfaceOrNull = OrNull<Interface>

const i: InterfaceOrNull = {
    a: null,
    b: null,
}

Playground here.

Sign up to request clarification or add additional context in comments.

Comments

0

Since it looks like CSS.Properties just expands the argument passed into it into the values of the object, you could simple add it to the CSS.Properties declaration:

import * as CSS from 'csstype';

type CSSProperties = CSS.Properties<number | string | null>;

let k: CSSProperties = {
  background: null,
  font: 'test',
  zIndex: 123,
  color: undefined
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.