[英]Tagged unions and tagging using literal types
在TypeScript 2.0中,引入了带标签的联合。 要使用它们,我们必须在接口中引入一个判别属性,例如:
interface Action {
type: "ACTION"
}
但是我不能使用字符串文字类型作为判别式:
let actionName: "ACTION"
interface Action {
type: actionName <- error: cannot find name "actionName"
}
我想知道这是功能还是错误。
您的字符串文字定义错误。 let
定义变量,而不是类型。 它应该是:
type actionName = "ACTION"
interface Action {
type: actionName;
}
解决方案是使用以下表示法:
const ACTION: "ACTION" = "ACTION"
interface Action {
type: typeof ACTION
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.