6.typescript.md

typescript

Typescript/flow, and typt aware linting.

typescript benefits:

  1. Catch type-related mistake
  2. Communicate type intent (类型推断)
  3. Provide IDE feedback

caveats

  1. Inferencing is best-guess, not a guarantee
  2. Annotations is optional
  3. Any part of the application that isn’t typed introduces uncertainty.

Inferencing:

在使用静态语言编写代码的时就会进行类型推断,并且与IDE很好的支持(有提示插件)。但是推断解决的问题是, 我们对一个变量不确定类型,很容易造成’xxx is undefined.’等error

在定义时就确定了类型, 在之后给该变量赋值使用不同的类型时,就会报错。

1
2
3
4
5
6
7
8
// example 1
var name = 'keywen'

name = {
value: 'keywen' // throw Error.
}
// example 2: 显示的确定其类型
var name: String = 'keywen'

custom type

自定义类型: 语法

1
2
3
4
5
6
7
8
// ":" 后是指定的类型
type student = {
name: string
}

function getName (studentObj: student): string {
return studentObj.name
}

Validating Operand Types

1
2
3
// case1,在这种情况下,我们不会触发强制, 只会在特定的类型进行运算, 防止出现我们意料之外的错误
var studentName: string = 'Nacy';
var studentSum: number = 16 - studentName; // throw error: can't substract sting

compare typescript with flow

不用比较了typescript已经赢了

两者主要是解决了我们在编程过程中对类型的不确定,让我们的类型更加清晰(前面说过了, 如果你对你代码中的类型不确定,那么, 最好的方式是重构你的代码, 因为你对你的代码还不够了解)

typescript的优点

  1. They make our code more obvious.
  2. more like other language’s systems.
  3. Extremely popular these days.(生态将会更好)
  4. 微软做背书,值得投资学习。
  5. They’re very sophisticated and good at what they do.(根据社区的反馈,他们做得非常好,至少在类型判断这一点上)

typescript的缺点

  1. They use “non-js-standard”syntax(or code comments)
    从长远看, 这是很危险的, 因为不使用标准语法, 那么在未来的某一天,js改了标准,而ts又改了足够多的东西,要么ts继续往js的标准走,要么ts成为另一种方言, 或者取代js
  2. They require a build process, which raises the barrier to entry
  3. Their sophistication can be intimidating to those without prior formal types experience(对于没有静态语言经历的同学就有点可怕了)
  4. They focus more on “static type”(variables, parameters, returns, properties)then value types.(ts更多的关注在变量的静态, 而不是值的静态)

我们知道,代码中的bug很大一部分是type问题造成的,那么ts和flow就解决了这个问题,但要意识到,这并不是唯一的解决方法

总结

  1. js本身拥有一个(动态)类型系统,它使用不同形式的强制转换,value的类型转换,运算符的转换, 等号两边的转换
  2. 然鹅,这样的类型系统大家给出的回应, 或者说解决方案是: 尽可能避免这样的系统,尽可能的使用”===”, 保护你担忧的类型
  3. 避免整个JS的部分问题,比如假装==避免了您需要了解类型,是它倾向于系统地使bug永久存在。在某些场景下,你最好还是使用“==”, 例如你非常了解你的类型系统时, 使用== 会让事情更简单,如果强行使用 === 那么这会造成系统级别的bug.
  4. 如果你不是足够的了解js的类型系统,那么就无法编写高质量的js代码.
  5. 使用静态语言系统或许是你的一个选择, 但不是唯一的解决方案。
  6. js的类型系统相对于静态语言来说的类型系统比较怪异, 但是学习它也是解决类型问题的一种方式
  7. 对于有过静态语言学习经验的开发者来说,js的类型系统对他们来说很难接受,而静态语言学习起来较为容易
  8. 我的主张:更好的方法是拥抱和学习JS的类型系统,并采用一种编码风格,使类型尽可能明显