我在下面的typeScript代码中尝试分配“字符串”或“空”值
<Document file="http://localhost:3000/dummy.pdf" />
现在,当我尝试将值分配给type MyValue = "A" | "B" | "C"
type Nullable<T> = T | null
let a: Nullable<MyValue> = null
时
a
其产生错误,例如
string'无法分配给Nullable
。怎么了?
答案 0 :(得分:2)
a = "A"
此处"A"
被解释为string
,不能分配给您的字符串文字类型。
只要做
a = "A" as const;
(因为我不确定as const
在ts 3.7中是否可用)
您也可以尝试
a = "A" as "A";
a = "A" as MyValue;