【发布时间】:2017-04-30 18:29:51
【问题描述】:
为什么tsc 不抱怨这行代码:
let a: 'my text string';
并允许a 为'my text string' 类型?
而且...如果有人利用隐式类型推断,只使用 ':' 而不是 '=',这不是很容易出错吗?!
【问题讨论】:
-
这叫做字面量类型。
标签: typescript types tsc
为什么tsc 不抱怨这行代码:
let a: 'my text string';
并允许a 为'my text string' 类型?
而且...如果有人利用隐式类型推断,只使用 ':' 而不是 '=',这不是很容易出错吗?!
【问题讨论】:
标签: typescript types tsc
这是一种文字类型。文档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(不仅仅是字符串)。然后,使用 TypeScript 2.1,文字类型为 are better inferred。
而且...如果有人利用隐式类型推断,只使用
':' 而不是'=',这不是很容易出错吗?!
在 TypeScript 中,需要识别 :。以下代码:
let a: 'my text string';
... 被编译为(这里是目标 ES6):
let a;
【讨论】: