0

在 TypeScript 2.0 中引入了标记联合。要使用它们,我们必须在接口中引入判别属性,例如:

interface Action {
    type: "ACTION"
}

但是我不能使用字符串文字类型作为判别式:

let actionName: "ACTION"

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

我想知道这是一个功能还是一个错误。

4

2 回答 2

0

解决方案是使用以下符号:

const ACTION: "ACTION" = "ACTION"

interface Action {
    type: typeof ACTION
}
于 2016-09-26T19:01:22.650 回答
0

您的字符串文字定义是错误的。let定义变量,而不是类型。它应该是:

type actionName = "ACTION"

interface Action {
    type: actionName;
}
于 2016-09-26T07:51:36.880 回答