【发布时间】:2018-04-22 14:24:00
【问题描述】:
考虑以下接口:
interface A {
name: string;
value: number;
sub: {
query: number[]
},
old: number;
}
interface B {
name: string;
value: string;
sub: {
query: string[]
},
new: boolean;
}
我正在寻找获取接口/类型的通用解决方案:
interface C extends B, A {
}
C 就像接口 D:
interface D {
name: string;
value: string;
sub: {
query: string[]
},
old: number;
new: boolean;
}
所以我可以有一个函数:
function merge<T, U>(t: T, u: U): interface C extends T, U {
// Merge objects
// ...
return obj;
}
它不一定是一个接口。类型也会这样做(我认为)。
A & B 类型不起作用,因为那时我有一个交叉点(例如,value 将是 number & string 类型)。
【问题讨论】:
-
除了 Intersection 类型之外,还有另一种高级类型 - Union Type,它可以接受数字或字符串的值。更多文档在这里 - typescriptlang.org/docs/handbook/advanced-types.html
-
A | Bunion 不会做你想做的事吗? -
没有。一个 | B 不一样。
标签: typescript types set-theory