[英]Typescript Tagged Union Types
I want to discriminate some logic according to what interface my function receives. 我想根据我的函数接收的接口区分一些逻辑。 To do this I'm attempting to use tagged union types, eg,
要做到这一点,我试图使用标记的联合类型,例如,
someFunction(arg: TypeA | TypeB): void {
if (arg.kind === "TypeA")
{
// do this
}
else
{
// do that
}
}
where 哪里
interface TypeA {
kind: "TypeA";
propertyA: string;
}
interface TypeB {
kind: "TypeB";
propertyB: string;
}
But if I want to call this function, Typescript complains if I don't provide a value for kind, ie, 但是如果我想调用这个函数,那么如果我没有为kind提供值,那么Typescript会抱怨,即
let typeA: TypeA;
typeA = {propertyA: ""}
someFunction(typeA);
with 同
TS2322: Type '{ propertyA: string; }' is not assignable to type 'TypeA'.
Property 'kind' is missing in type '{ propertyA: string; }'.
So I don't understand how tagged types work if I have to implement the tag ( kind
in the example above) every time I want to discriminate. 所以,我不明白类型是如何工作的标记,如果我要实现的标签(
kind
在上面的例子中),我想区分每一次。 I can only assume I'm using them wrong? 我只能假设我使用它们错了?
You can define a type guard to do this. 您可以定义类型保护来执行此操作。 They allow you to tell the type of an argument by the value or existence of one of it's properties.
它们允许您通过其中一个属性的值或存在来告知参数的类型。
function isTypeA(arg: TypeA | TypeB): arg is TypeA {
return (<TypeA>arg).propertyA !== undefined;
}
function someFunction(arg: TypeA | TypeB): void {
if (isTypeA(arg))
{
arg.propertyA;
}
else
{
arg.propertyB
}
}
You can read more about them here and check a working example here . 你可以阅读更多关于他们在这里检查工作的例子在这里 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.