将接口或类型的所有属性扩展为可能为空

时间:2020-07-15 20:32:59

标签: typescript

我的类型如下:

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

,需要将其转换为:

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

,其中所有属性都可能为空。 (在可以使用“部分”的地方未定义)

是否可以通过编程方式执行此操作?我已经尝试过像这样的映射类型:

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

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

,但是第一个(联合)的结果类型是基类型的对象或具有所有null属性的对象,而第二个(交集)的结果是“ never”类型的所有属性,因为null而不会。 t与非null类型的“重叠”。

1 个答案:

答案 0 :(得分:3)

您几乎可以通过映射类型尝试获得它。但是您需要包括键值的原始类型,然后将其与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.

相关问题