dstaley
dstaley

Reputation: 1052

Extend a TypeScript interface to allow its keys to be null

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.

Upvotes: 1

Views: 1958

Answers (2)

Jeremy
Jeremy

Reputation: 180

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
};

Upvotes: 0

Lazar Ljubenović
Lazar Ljubenović

Reputation: 19764

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.

Upvotes: 4

Related Questions