简体   繁体   English

带标记的联合和使用文字类型的标记

[英]Tagged unions and tagging using literal types

In TypeScript 2.0 there were introduced tagged unions. 在TypeScript 2.0中,引入了带标签的联合。 To use them we have to introduce a discriminant property in interface, for example: 要使用它们,我们必须在接口中引入一个判别属性,例如:

interface Action {
    type: "ACTION"
}

However I'm not able to use string literal type as a discriminant: 但是我不能使用字符串文字类型作为判别式:

let actionName: "ACTION"

interface Action {
    type: actionName <- error: cannot find name "actionName"
}

I'm wondering if it's a feature or a bug. 我想知道这是功能还是错误。

Your string literal definition is wrong. 您的字符串文字定义错误。 let defines variable, not a type. let定义变量,而不是类型。 It should be: 它应该是:

type actionName = "ACTION"

interface Action {
    type: actionName;
}

The solution is to use the following notation: 解决方案是使用以下表示法:

const ACTION: "ACTION" = "ACTION"

interface Action {
    type: typeof ACTION
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM