繁体   English   中英

Typescript如何推断组合类型

[英]Typescript How to infer Combinded Types

interface Base<T> {
    values: T[];
}

interface HaveA<T> extends Base<T> {
    a?: number;
}

interface HaveB<T> extends Base<T> {
    b?: number;
}

interface HaveC<T> extends Base<T> {
    c?: number;
}

type SetA<V, X> = V extends Base<X> ? V & HaveA<X> : HaveA<V>;
type SetB<V, X> = V extends Base<X> ? V & HaveB<X> : HaveB<V>;
type SetC<V, X> = V extends Base<X> ? V & HaveC<X> : HaveC<V>;


type A = SetA<string, string>; // HaveA<string>, right
type AB = SetB<A, string>; // HaveA<string> & HaveC<string>, right
type ABC = SetC<AB, string>; // HaveC<string>, wrong

我想从原始类型以任何组合形式输入类型。 A: {a}, B: {b}, C:{c}, AB:{a, b}, AC:{a, c}, BC:{b, c}, ABC: {a, b, c}

用于组合每种类型的&运算符。 用于extends Base ,以确保该类型已扩展到任何字符。 但似乎不是检查它的正确运算符。

如何检查typetype & type 除了使用&之外,还有其他组合方式吗?

我解决了使用'values' in keyof V作为临时方法。 某些接口可能没有“值”。

添加:

interface Base<T> {
    items: T[];
}

interface A<T> extends Base<T> {
    a: number;
}

interface B<T> extends Base<T> {
    b: number;
}

interface C<T> extends Base<T> {
    c: number;
}

type Arg<T, U> = T extends null ? U : T & U;
type DataA<T> = T extends { items: Array<infer X> } ? T & A<X> : A<T>;
type DataB<T> = T extends { items: Array<infer X> } ? T & B<X> : B<T>;
type DataC<T> = T extends { items: Array<infer X> } ? T & C<X> : C<T>;


class Types<T, U> {
    set<V>() {
        return this as any as Types<Arg<T, V>, U>;
    }

    setA() {
        return this as any as Types<Arg<T, { a: number }>, DataA<U>>;
    }

    setB() {
        return this as any as Types<Arg<T, { b: number }>, DataB<U>>;
    }

    setC() {
        return this as any as Types<Arg<T, { c: number }>, DataC<U>>;
    }

    test(t: T) {
    }

    test2(f: (args: U) => void) {
        f(<U>{});
    }
}

const types = new Types<null, number>();

types
    .set<null>()
    .set<{ foo: string }>()
    .set<{ bar: string }>()
    .setA()
    .setB()
    .setC()
    .test2(d => {});

这类似于我的上一个测试代码。 当我写问题时。 我的IDE也有滞后和错误。
我不知道我的IDE为什么能正常工作。

我不是傻瓜,也许世界恨我

您的代码在操场上对我有用 (链接太长,无法在注释中添加)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM