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
确保该类型已扩展到任何字符。但它似乎不是一个正确的运算符来检查它。
如何在type & type
中查看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工作正常。
我不是傻子,也许全世界都恨我
发布于 2018-09-10 08:34:23
你的代码适用于我的in the playground (链接太长,不能放在评论中)。
https://stackoverflow.com/questions/52198951
复制相似问题