2.1版本后使用打字稿的意义

时间:2017-08-02 16:13:40

标签: typescript types

谁能告诉我今天使用打字稿的目的是什么?我确信人们主要使用打字稿来避免由类型引起的一些错误。但是在第2.1节之后,下面的代码是可以接受的:

let i;

let aNumber = (x:number) => {
  x = 52;
  console.log(x);
}

aNumber(i);

let aString = (x:string) => {
  x = 'strung';
  console.log(x);
}

aString(i);

这真的让我的想象力蹒跚...我是一个心胸狭窄或打字的作者吗?谢谢你的公平答案!

此致 crova

2 个答案:

答案 0 :(得分:1)

您实际上可以配置(null和)undefined类型的处理。见https://www.typescriptlang.org/docs/handbook/basic-types.html#null-and-undefined

  

默认情况下,nullundefined是所有其他类型的子类型。这意味着您可以将nullundefined分配给number

     

但是,使用--strictNullChecks标记时,nullundefined只能分配给void及其各自的类型。这有助于避免许多常见错误。如果您要传递stringnullundefined,则可以使用联合类型string | null | undefined

另见https://www.typescriptlang.org/docs/handbook/compiler-options.html

strictNullChecks编译器标志实际上是introduced in TypeScript 2.0

答案 1 :(得分:0)

如果打开strictNullChecks编译器选项,则代码会抛出错误,提示“未定义不可分配给数字”。

查看compiler options

在v2.1之前,非隐式变量被隐式推断为any,它在v2.1的improved type inference之后被更改。