从 TypeScript 中的类型中删除 Null 和 Undefined
Remove Null and Undefined from a Type in TypeScript
使用实用程序类型从 TypeScript 中的类型中NonNullable
删除null
和删除。undefined
实用程序NonNullable
类型构造一个新类型,null
并
undefined
从该类型中排除。
索引.ts
type Salary = null | undefined | number;
// 👇️ type T0 = number
type T0 = NonNullable<Salary>;
NonNullable
实用程序类型从传入类型中排除null
和。undefined
索引.ts
type Name = null | undefined | string;
// 👇️ type T2 = string
type T2 = NonNullable<Name>;
示例中的联合由null
,undefined
和组成string
。
一旦传递给NonNullable
实用程序类型,结果只有
string
.
所有不可为 null 的类型都保留在结果中。
索引.ts
type Employees = null | undefined | string | string[];
// 👇️ type T2 = string | string[]
type T2 = NonNullable<Employees>;
NonNullable
递归使用类型
但是,在某些情况下,您可能需要递归地使用类型NonNullable
,以使类型中的所有键都不可为空。
索引.ts
type WithoutNullableKeys<Type> = {
[Key in keyof Type]-?: WithoutNullableKeys<NonNullable<Type[Key]>>;
};
type Employee = {
name?: string | null;
country?: string | null;
salary?: number | null;
};
// 👇️ type T1 = {
// name: string;
// country: string;
// salary: number;
// }
type T1 = WithoutNullableKeys<Employee>;
该-?
语法称为
映射修饰符
,用于将类型的属性设置为必需(删除可选性)。
索引.ts
type Employee = {
name?: string | null;
country?: string | null;
salary?: number | null;
};
type Concrete<Type> = {
[Key in keyof Type]-?: Type[Key];
};
// 👇️ type T2 = {
// name: string | null;
// country: string | null;
// salary: number | null;
// }
type T2 = Concrete<Employee>;
该示例显示了该类型如何Concrete
使所有键成为Employee
必需的。
这种方法也可用于从
接口null
中删除和删除。undefined
索引.ts
type WithoutNullableKeys<Type> = {
[Key in keyof Type]-?: WithoutNullableKeys<NonNullable<Type[Key]>>;
};
interface Employee {
name?: string | null;
country?: string | null;
salary?: number | null;
}
// 👇️ type T1 = {
// name: string;
// country: string;
// salary: number;
// }
type T1 = WithoutNullableKeys<Employee>;