为什么可以在 TypeScript 中声明 'anyTextString' 类型的变量?
Why is it possible to declare a variable of 'anyTextString' type in TypeScript?
为什么 tsc
不抱怨这行代码:
let a: 'my text string';
并允许 a
为 'my text string'
?
类型
而且...如果有人利用隐式类型推断,并且只是放置 ':
' 而不是 '='
,这不是很容易出错吗?!
这是文字类型。文档 is here。一个例子:
type Color = 'blue' | 'red'
function showColor(c: Color) {
console.log(c)
}
showColor('blue') // OK
showColor('other') // Error
注意:自 TypeScript 2.0 起,文字类型为 expanded to numbers and booleans (not only strings). Then, with TypeScript 2.1, literal types are better inferred.
And... Isn't this bug-prone if, let's say, someone takes advantage of implicit type inference, and just puts a ':
' instead of '='
?!
在 TypeScript 中,需要识别 :
。以下代码:
let a: 'my text string';
... 编译为(此处目标为 ES6):
let a;
为什么 tsc
不抱怨这行代码:
let a: 'my text string';
并允许 a
为 'my text string'
?
而且...如果有人利用隐式类型推断,并且只是放置 ':
' 而不是 '='
,这不是很容易出错吗?!
这是文字类型。文档 is here。一个例子:
type Color = 'blue' | 'red'
function showColor(c: Color) {
console.log(c)
}
showColor('blue') // OK
showColor('other') // Error
注意:自 TypeScript 2.0 起,文字类型为 expanded to numbers and booleans (not only strings). Then, with TypeScript 2.1, literal types are better inferred.
And... Isn't this bug-prone if, let's say, someone takes advantage of implicit type inference, and just puts a
':
' instead of'='
?!
在 TypeScript 中,需要识别 :
。以下代码:
let a: 'my text string';
... 编译为(此处目标为 ES6):
let a;