【问题标题】:DeepPartial: use null instead of undefinedDeepPartial:使用 null 而不是 undefined
【发布时间】:2020-11-19 03:12:25
【问题描述】:

utility-types 中的DeepPartial 泛型类型应用于Typescript 类型时,我注意到所有属性的类型都自动扩展为包括undefined。 IE。以前类型为 T 的属性现在变为 T | undefined

例如以下代码未通过类型检查:

import { DeepPartial } from 'utility-types';

type A = { a1: number, a2: number};
type B = DeepPartial<A>;

const b: B = { a1: null };

Typescript Playground 是 here

我知道这也是普通的 Partial 所做的。但是有没有更深层次的原因为什么选择| undefined(在这两种情况下)而不是相反,例如to:| null| null | undefined,有没有办法可以自定义 DeepPartial 泛型类型,以便使用 | null 生成属性类型?

【问题讨论】:

    标签: typescript typescript-generics typechecking type-constraints


    【解决方案1】:

    Partial&lt;T&gt; 的目的是将{x: number, y: string} 之类的类型转换为属性都是可选的类型,例如{x?: number, y?: string}。在这种情况下,属性的类型是number | undefinedstring | undefined,因为? 表示允许丢失该属性,而undefined 是访问丢失的属性时得到的。

    要获取null 而不是undefined,您只需获取source code for DeepPartial 并对其进行调整:

    type DeepNullable<T> = T extends Function
        ? T
        : T extends Array<infer U>
        ? _DeepNullableArray<U>
        : T extends object
        ? _DeepNullableObject<T>
        : T | null;
    
    interface _DeepNullableArray<T> extends Array<DeepNullable<T>> {}
    
    type _DeepNullableObject<T> = { [P in keyof T]: DeepNullable<T[P]> | null };
    

    演示:

    type Foo = {
        foo: number,
        bar: {
            baz: Array<{ quz: string }>
            qux: boolean
        }
    }
    
    // test has no type errors
    let test: DeepNullable<Foo> = {
        foo: null,
        bar: {
            baz: [{quz: null}, {quz: null}],
            qux: null
        }
    }
    

    Playground Link

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多