Typescript 是否支持互斥类型? [英] Does Typescript support mutually exclusive types?
本文介绍了Typescript 是否支持互斥类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个接受参数的方法.我希望 Typescript 验证传入的对象(在 typescript 编译时,我理解运行时是一种不同的动物)仅满足一个允许的接口.
I have a method that takes a parameter. I would like Typescript to verify that the object being passed in (at typescript compile-time, I understand run-time is a different animal) only satisfies one of the allowed interfaces.
示例:
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,但这是我想尝试的第一件事,而且看起来很合理.
I realize that Person ^ Pet
is not valid Typescript, but it's the first thing I thought to try and seemed reasonable.
推荐答案
As proposed in this issue, you could use conditional types to write a XOR type:
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 是否支持互斥类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文