TS Basic

91 阅读1分钟

Why TS

popular TS vs. JS

  1. ts is more than js
  2. Support for static and dynamic types
  3. Errors can be found and corrected during Compilation
  4. change of data type is forbidden

What can we get when using TS: datatype safety, new js feature, complete tool chain.

Recommend Resources: AwesomeTS, playground essential

ts Basic

Data Type

  1. boolean ,number ,string
  2. enum
  3. any ,unknown , void
  4. never 不存在值,防御
  5. Arr[]数组
  6. tuple 元组

函数重载,多次定义,前几次是定义,最后一次是实现

function add(x:number[]):number
function add(x:string[]):string
function add(x:any[]):any{
    if(typeof x[0]==='string'){
        return x.json()
    }
    if(typeof x[0]==='number'){
        return x.reduce((acc,cur)=> acc + cur)
    }
}

Interface,接口 Def: to define object types Feature:

- optional properties: ?
- readOnly:
- describe Function type
- describe custom properties 

Class

  • public
  • private
  • protected

ts Advanced

  1. 联合类型 | Union Types

    let tag:Type1|Type2|Type3

  2. 交叉类型 &

  3. 类型断言

  4. 类型别名

泛型

基本定义:/Basic Def

  1. syntax
function print<T>(arg:T){
    ....
}
  1. There are two ways to specify the type of use.

    1. Define the type to be used
    2. Automatically deduce the type by typescript type inference
  2. temperary occupancy

Basic Operators

  • typeof
  • keyof
  • in
  • T[K]
  • extends

Tool types

  • Partical<T>可选
  • Required<T>必选
  • Readonly<T>只读

TS in practice

声明文件/不确定要怎么翻译,查了再改

  • declare
  • .d.ts
  • @types
  • tsconfig.json

Q&A

  1. Why sometimes Ts to AnyScript 这是很常见的情况
    • 存量项目改造:改造成本,逐渐完善
    • 新建项目:建议定义类型