我有一个接受参数的方法。我希望 Typescript 验证传入的对象(在 Typescript 编译时,我知道运行时是另一种动物)仅满足一个允许的接口(interface)。
例子:
interface Person {ethnicity: string;}
interface Pet {breed: string;}
function getOrigin(value: Person ^ Pet){...}
getOrigin({}); //Error
getOrigin({ethnicity: 'abc'}); //OK
getOrigin({breed: 'def'}); //OK
getOrigin({ethnicity: 'abc', breed: 'def'});//Error
我意识到 Person ^ Pet
不是有效的 Typescript,但这是我首先想到的,而且看起来很合理。
最佳答案
如 this issue 中所提议, 你可以使用 conditional types编写异或类型:
type Without<T, U> = { [P in Exclude<keyof T, keyof U>]?: never };
type XOR<T, U> = (T | U) extends object ? (Without<T, U> & U) | (Without<U, T> & T) : T | U;
现在你的例子有效了:
interface Person {ethnicity: string;}
interface Pet {breed: string;}
function getOrigin(value: XOR<Person, Pet>) { /* ... */}
getOrigin({}); //Error
getOrigin({ethnicity: 'abc'}); //OK
getOrigin({breed: 'def'}); //OK
getOrigin({ethnicity: 'abc', breed: 'def'});//Error
关于typescript - Typescript 是否支持互斥类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42123407/