分配的表达式类型“ X”不能分配给类型“ X” | “ Y”

时间:2019-06-17 04:56:00

标签: angular typescript webstorm

我从Angular模板中收到此错误:

  

分配的表达式类型“默认”不能分配给类型“默认” | “删除” | “重命名”`

在显示currentAction = 'default'的行上:

enter image description here

但是我的currentAction变量是这样声明的:

type Action = 'default' | 'delete' | 'rename';
public currentAction: Action = 'default';

所以我认为分配它是有效的,因为default是有效值。

如果我在组件的类(而不是模板)中执行类似的操作,则没有警告也没有错误:

this.currentAction = 'default'

这看起来像是我的IDE(WebStorm)的错误还是在Angular模板中分配该变量有问题?

2 个答案:

答案 0 :(得分:2)

这是IDE中的错误,已在即将于2019.2。中修复。 请尝试2019.2 EAP-在那里似乎可以正常工作:

enter image description here

答案 1 :(得分:-1)

该行为足够正确,因为可以更改类型,因此IDE无法确定字符串值'default'将来是否适合该类型。

在这种情况下,最好使用enums,因为您可以使用值并进行更改而不会出现任何问题:

enum Action {
    DEFAULT = 'default',
    DELETE = 'delete',
    RENAME = 'rename'
}