【问题标题】:Why is it possible to declare a variable of 'anyTextString' type in TypeScript?为什么可以在 TypeScript 中声明“anyTextString”类型的变量?
【发布时间】:2017-04-30 18:29:51
【问题描述】:

为什么tsc 不抱怨这行代码:

let a: 'my text string';

并允许a'my text string' 类型?

而且...如果有人利用隐式类型推断,只使用 ':' 而不是 '=',这不是很容易出错吗?!

【问题讨论】:

  • 这叫做字面量类型。

标签: typescript types tsc


【解决方案1】:

这是一种文字类型。文档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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-29
    • 1970-01-01
    • 2014-05-07
    • 1970-01-01
    • 2020-05-16
    • 1970-01-01
    • 2021-07-27
    • 2015-07-25
    相关资源
    最近更新 更多