【发布时间】:2020-07-26 09:42:16
【问题描述】:
对于typescript 的literal types,无论我们使用常规加法运算符(例如a = a + b)还是加法赋值运算符(例如a += b),行为都是不同的:
type SomeLiteralType = 1;
let a: SomeLiteralType = 1;
// Why is it possible to change the value of Literal type to unsupported value without any error?
a += 1;
// Now it's even not allowed to assign to itself - next error occurs: "Type 'number' is not assignable to type '1'"
a = a;
所以最终使用加法赋值运算符我们可以强制变量包含意外值。
字符串也是如此。
这是预期的行为吗?我在文档中遗漏了一些内容?
【问题讨论】:
标签: typescript language-design assignment-operator