对于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;
因此最终使用加法赋值运算符,我们可以强制变量包含意外值。
字符串也一样。
这是预期的行为,我错过了文档中的某些内容吗?
1)关于类型检查过程,c += b;
和a += a;
相等。可以在4)
中找到发生了什么的解释。
2)d = d + b;
该表达式将由编译器解释如下:作业表达:左侧:d
令牌(运营商):=
右侧:d + b
为了检查双方的类型,编译器会为左右表达式扣除类型。在左侧的情况下很简单。右边是数字。原因是所有数学运算符(+
,-
,...)仅可用于数字(在jJavaScript中),因此结果也必须为数字类型。在左侧扣除类型Odd
,在右侧扣除数字,您将得到错误。
3)e = a + a;
像上面的行一样[2)
)
4)a += a;
该表达式归纳如下:作业表达:左侧:a
令牌(运营商):+=
右侧:a
从上面我们知道,所有数学运算符只能应用于数字,这应该是不言自明的。编译器检查左侧是否为数字,a
是什么,如果右边是数字。 a
或1
都是数字,因此可以使用。
为什么最后一行现在应该清楚了,我将其留作功课;)