简体   繁体   中英

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

I want to make type in any combination from origin type. like A: {a}, B: {b}, C:{c}, AB:{a, b}, AC:{a, c}, BC:{b, c}, ABC: {a, b, c}

used & operator for combine each types. used extends Base to make sure that type already extended to any characters. but It seems to not a correct operator for check for it.

how to check the type in type & type ? have there other way for combine type except using & ?

I solved it use 'values' in keyof V as temporary way. some interface may will have not 'values'.

ADDED:

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 => {});

This is similar to my last test codes. when I wrote question. My IDE has lag and error too.
I don't know why my IDE working correct.

I'm not a fool, maybe world hate me

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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