- 为什么要使用TS?不用能死吗?
这是一个很有意思的问题,归纳一下使用TS的原因如下
- 增加程序的健壮性,可以在编码时就预设了程序的运行状态,避免了JS中动态类型带来的不可预知的错误。 ```typescript function fn(x) { return x.flip(); } // 当调用fn函数的时候,传入的参数必须包含一个filp属性,并且其对应的值必须是可调用的,但是纯JS代码在运行的时候,fn被调用时,无法保证fn调用者为其传入了正确的类型,容易引发未知错误 fn(1) // Uncaught TypeError: x.flip is not a function
2. 当面对一个对象或者方法的时候,我们会问如下的问题,而使用TS可以在编码时避免这些问题。1. 这个对象可以调用吗?1. 这个对象包含哪些属性和方法?1. 这个对象如果可以调用会返回什么?3. 使用TS还能纠正一些不容易察觉的拼写错误,可以在写代码犯错时抛出错误。2. 静态类型检查2. 非异常错误1. 一般来说,对于纯JS,访问对象上一个不存在的属性,会返回undefined,但是TS则会在编码时给出提示。```typescriptconst user = {name: "Daniel",age: 26,};user.location; // Property 'location' does not exist on type '{ name: string; age: number; }'.
b. 未调用的函数
function flipCoin() {// Meant to be Math.random()return Math.random < 0.5; // Operator '<' cannot be applied to types '() => number' and 'number'.}
c. 基本的逻辑错误
const value = Math.random() < 0.5 ? "a" : "b";if (value !== "a") {// ...} else if (value === "b") {//This condition will always return 'false' since the types '"a"' and '"b"' have no overlap.// Oops, unreachable}
- 类型工具
- 代码补全
- 与编辑器结合紧密
- 属性建议
- 快速修复错误
- 类型定义快速跳转
- 完全跨平台
- tsc, the TypeScript compiler
我们一直在讨论类型检查,但是还没有使用过type-checker(类型检查器),我们可以用过npm的方式得到他
npm install -g typescript
tsc可以对 .ts 文件进行编译,在指定目录下生成对应的.js文件,并对错误进行相应提示
// hello.ts// This is an industrial-grade general-purpose greeter function:function greet(person, date) {console.log(`Hello ${person}, today is ${date}!`);}greet("Brendan");
对hello.ts进行编译
tsc hello.ts// Expected 2 arguments, but got 1.
tsc对我们代码中存在的错误进行了提示,感谢TypeScript
- Emitting With Errors
默认情况下,即使xxx.ts文件有错误,经过tsc编译,也会生成xxx.js文件,但是如果我们不想在有错误的情况下生成js文件可以使用noEmitOnError属性
tsc --noEmitOnError hello.ts
- 显式类型
我们可以显式的为一个参数指定类型,这样可以方便的使用其对应的属性或方法,如下,我们显式的指定了greet函数的两个参数的类型。
function greet(person: string, date: Date) {console.log(`Hello ${person}, today is ${date.toDateString()}!`);}
但是TypeScript还有一个特性是可以推断出一个变量类型,如下,msg会被自动推断为string, 这是一个特性,如果类型系统可以自动推断一个变量的类型,我们最好不要去加类型注释。
let msg = "hello there!";
