Extend all properties of Interface or Type to be potentially null

Viewed 734

I have a type like:

type Base = {
  propA: number;
  propB: string;
}

and need to convert it to:

type BaseWithNull = {
  propA: number | null;
  propB: string | null;
}

where all properties are potentially null. (NOT undefined where you could use "Partial")

is it possible to do this programmatically? I've experimented with mapped types like this:

type BaseWithNull = Base | {
    [P in keyof BaseRemoteWeatherForecast]: null;
};

type BaseWithNull = Base & {
    [P in keyof BaseRemoteWeatherForecast]: null;
};

but the first (union) results in a type where it's either an object with the Base type or an object with all null properties, while the second (intersection) results in all properties as "never" types since null and doesn't "overlap" with non-null types.

1 Answers

You almost have it with your mapped type attempt. But you need to include the original type of the key's value and then union it with null:

type WithNull<T> = {
    [P in keyof T]: T[P] | null;
}

type BaseWithNull = WithNull<Base>;

declare const test: BaseWithNull;
const nullable_number = test.propA; // Has type number | null

Typescript Playground.

Related