选择可为空的属性并使它们不可为空的一般方法

时间:2018-11-01 14:09:09

标签: typescript

让我们有以下示例类型:

interface A {
    a?: number;
    b: string;
}

我的目标是拥有创建以下类型的通用方法:

interface ExpectedA {
    a: number;
}

所以我想删除所有不可为空的字段(可以包含null和/或undefined的字段),并使其余的可为空的字段不可为空。

这是我想它应该起作用的方式:

const expA1: ExpectedA = {}; // should NOT pass
const expA2: ExpectedA = {a: 1}; // should pass
const expA3: ExpectedA = {b: ''}; // should NOT pass
const expA4: ExpectedA = {c: 0}; // should NOT pass
const expA5: ExpectedA = {a: 1, b: ''}; // should NOT pass

这是我不工作的尝试(在注释中注明了它的作用和应该的作用):

export type ExtractNullable<T> = {
    [K in keyof T]: T[K] extends undefined | null ? NonNullable<T[K]> : never;
};

const a1: ExtractNullable<A> = {}; // should NOT pass, wrong error "prop. b is missing"
const a2: ExtractNullable<A> = {a: 1}; // should pass, wrong - "number not undefined"
const a3: ExtractNullable<A> = {b: ''}; // should NOT pass, wrong - "string not never"
const a4: ExtractNullable<A> = {c: 0}; // should NOT pass, ok - "c not on ..."
const a5: ExtractNullable<A> = {a: 1, b: ''}; // should NOT pass, wrong error "number not undefined, string not never"

我认为问题出在条件类型上,但查看文档,我不知道要更改什么。

1 个答案:

答案 0 :(得分:2)

您只需要先选择可为空的键,然后再映射它们即可。

interface A {
    a?: number;
    b: string;
}

export type NullableKeys<T> = {
    [P in keyof T]-? :  Extract<T[P], null | undefined> extends never ? never: P
}[keyof T]
export type ExtractNullable<T> = {
    [P in NullableKeys<T>]: NonNullable<T[P]>
}

const a1: ExtractNullable<A> = {}; // err
const a2: ExtractNullable<A> = {a: 1}; //ok
const a3: ExtractNullable<A> = {b: ''}; // err
const a4: ExtractNullable<A> = {c: 0}; // err
const a5: ExtractNullable<A> = {a: 1, b: ''}; //err

上述方法适用于strictNullChecks,因为可选属性的类型已更改为包括undefined。选择可选属性并且在没有此编译器选项的情况下可以运行的版本是:

export type NullableKeys<T> = {
    [P in keyof T]-?:  Pick<T,P> extends Required<Pick<T, P>> ? never: P
}[keyof T]
相关问题