从 TypeScript 中的类型中删除 Null 和 Undefined

710 阅读1分钟

从 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>;