gpt4 book ai didi

typescript - 从类型的属性中删除 null 或 undefined

转载 作者:搜寻专家 更新时间:2023-10-30 21:02:23 25 4
gpt4 key购买 nike

我需要声明一个类型,以便从其属性类型中删除未定义。

假设我们有:

type Type1{
prop?: number;
}

type Type2{
prop: number | undefined;
}

type Type3{
prop: number;
}

我需要定义一个名为 NoUndefinedField<T> 的通用类型这样 NoUndefinedField<Type1>给出与 Type3 相同的类型与 NoUndefinedField<Type2> 类型相同.

我试过了

type NoUndefinedField<T> = { [P in keyof T]: Exclude<T[P], null | undefined> };

但它只适用于 Type2 .

最佳答案

使用 NonNullable 内置类型:

type NonNullable<T> = Exclude<T, null | undefined>;  // Remove null and undefined from T

参见 TypeScript: Documentation - Utility Types

关于typescript - 从类型的属性中删除 null 或 undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53050011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com