1. 为什么要使用TS?不用能死吗?

    这是一个很有意思的问题,归纳一下使用TS的原因如下

    1. 增加程序的健壮性,可以在编码时就预设了程序的运行状态,避免了JS中动态类型带来的不可预知的错误。 ```typescript function fn(x) { return x.flip(); } // 当调用fn函数的时候,传入的参数必须包含一个filp属性,并且其对应的值必须是可调用的,但是纯JS代码在运行的时候,fn被调用时,无法保证fn调用者为其传入了正确的类型,容易引发未知错误 fn(1) // Uncaught TypeError: x.flip is not a function
    1. 2. 当面对一个对象或者方法的时候,我们会问如下的问题,而使用TS可以在编码时避免这些问题。
    2. 1. 这个对象可以调用吗?
    3. 1. 这个对象包含哪些属性和方法?
    4. 1. 这个对象如果可以调用会返回什么?
    5. 3. 使用TS还能纠正一些不容易察觉的拼写错误,可以在写代码犯错时抛出错误。
    6. 2. 静态类型检查
    7. 2. 非异常错误
    8. 1. 一般来说,对于纯JS,访问对象上一个不存在的属性,会返回undefined,但是TS则会在编码时给出提示。
    9. ```typescript
    10. const user = {
    11. name: "Daniel",
    12. age: 26,
    13. };
    14. user.location; // Property 'location' does not exist on type '{ name: string; age: number; }'.

    b. 未调用的函数

    1. function flipCoin() {
    2. // Meant to be Math.random()
    3. return Math.random < 0.5; // Operator '<' cannot be applied to types '() => number' and 'number'.
    4. }

    c. 基本的逻辑错误

    1. const value = Math.random() < 0.5 ? "a" : "b";
    2. if (value !== "a") {
    3. // ...
    4. } else if (value === "b") {
    5. //This condition will always return 'false' since the types '"a"' and '"b"' have no overlap.
    6. // Oops, unreachable
    7. }
    1. 类型工具
      1. 代码补全
      2. 与编辑器结合紧密
        1. 属性建议
        2. 快速修复错误
        3. 类型定义快速跳转
        4. 完全跨平台
    2. tsc, the TypeScript compiler

    我们一直在讨论类型检查,但是还没有使用过type-checker(类型检查器),我们可以用过npm的方式得到他

    1. npm install -g typescript
    1. tsc可以对 .ts 文件进行编译,在指定目录下生成对应的.js文件,并对错误进行相应提示
    1. // hello.ts
    2. // This is an industrial-grade general-purpose greeter function:
    3. function greet(person, date) {
    4. console.log(`Hello ${person}, today is ${date}!`);
    5. }
    6. greet("Brendan");
    1. hello.ts进行编译
    1. tsc hello.ts
    2. // Expected 2 arguments, but got 1.
    1. tsc对我们代码中存在的错误进行了提示,感谢TypeScript
    1. Emitting With Errors

    默认情况下,即使xxx.ts文件有错误,经过tsc编译,也会生成xxx.js文件,但是如果我们不想在有错误的情况下生成js文件可以使用noEmitOnError属性

    1. tsc --noEmitOnError hello.ts
    1. 显式类型

    我们可以显式的为一个参数指定类型,这样可以方便的使用其对应的属性或方法,如下,我们显式的指定了greet函数的两个参数的类型。

    1. function greet(person: string, date: Date) {
    2. console.log(`Hello ${person}, today is ${date.toDateString()}!`);
    3. }
    1. 但是TypeScript还有一个特性是可以推断出一个变量类型,如下,msg会被自动推断为string, 这是一个特性,如果类型系统可以自动推断一个变量的类型,我们最好不要去加类型注释。
    1. let msg = "hello there!";
    1. https://www.typescriptlang.org/docs/handbook/2/basic-types.html#erased-types