通过属性类型中提取值

时间:2019-02-03 02:15:40

标签: typescript

following code我通过类型想滤波器特性:

interface Wrapper<T> {
    x: T;
}

interface WrapperOpt<T> {
    y?: T;
}

interface A {
    a1: number;
    a2: Wrapper<number>;
    a3: WrapperOpt<number>;

    b1?: string;
    b2?: Wrapper<string>;
    b3?: WrapperOpt<string>;
}

type Wrapped = { [key in keyof A]: A[key] extends Wrapper<infer T> ? T : never };
type WrappedOpt = { [key in keyof A]: A[key] extends WrapperOpt<infer T> ? T : never };

它与类型Wrapper一起使用,给了我Wrapped,其中只有a2b2不是never

type Wrapped = {
    a1: never;
    a2: number;
    a3: never;
    b1?: never;
    b2?: string;
    b3?: never;
}

但这不适用于WrapperOpt给我WrappedOpt的情况:

type WrappedOpt = {
    a1: {};
    a2: {};
    a3: {};
    b1?: {};
    b2?: {};
    b3?: {};
}

但是我希望它的a3b3具有正确的类型,而所有其他类型都不会具有:

type Wrapped = {
    a1: never;
    a2: never;
    a3: number;
    b1?: never;
    b2?: never;
    b3?: string;
}

我该如何解决?

顺便说一句,将来我将按照this description的类型去掉never并变得干净:

type Wrapped = {
    a2: number;
    b2?: string;
}

type WrappedOpt = {
    a3: number;
    b3?: string;
}

1 个答案:

答案 0 :(得分:0)

找到了解决方案:检查extends左类型时,必须将其包装到Required中:

type WrappedOpt = { [key in keyof A]: Required<A[key]> extends WrapperOpt<infer T> ? T : never };