TypeScript中的数据类型(上)

88 阅读2分钟

一、 JavaScript和TypeScript 中的数据类型

  • JavaScript
    nullundefinednumberbooleanstringbigintsymbolobject(ArrayFunctionObject...)
    
  • TypeScript
    1nullundefinednumberbooleanstringbigint(比如 100n)、symbolobject(ArrayFunctionObject...)
    2voidneverenum、unknow、any
    3、自定义类型:typeinterface
    

二、如何在TS里描述对象的数据类型

  • 1、用 class / constructor 描述(js里class就是constructor)
    // Array、Date 就是 class/constructor 
    const a: Array<number> = [1]
    const d: Date = new Date()
    
  • 2、用 type 或 interface 描述
    type A = {
        name: string
        age: number
    }
    const a: A = {
        name: 'rourou',
        age: 18
    }
    type B = {
        [k: string]: number
    }
    const b: B = {
        age: 18,
        other: 20
    }
    type C = Record<string, number> // 等价于 type B
    const c: C = {
        age: 18,
        other: 20
    }
    

三、使用 TS 来描述数组对象

  • 如下

    // 方式 1
    // A 等价于 B
    type A = string[]
    const a: A = ['a', 'b']
    type B = Array<string>
    const b: B = ['c', 'd']
    // 方式 2
    type C = [number, number, number] // 三元组
    const c: C = [1, 2.6, 3]
    // 方式 3
    const r: Record<number, number> = [1, 2]
    // 多类型数组
    type D = [string, number] // 二元组
    const d: D = ['e', 4]
    // 数组套数组
    type E = [string[], number[]] // 二元组
    const e: E = [['1', '2'], [2, 3]]
    

四、使用 TS 来描述函数对象

  • 如下
    // 1.有返回值
    type FnA = (a: number, b: number) => number
    // 2.没有返回值
    type FnReturnVoid = (s: string) => void
    const v: FnReturnVoid = (s: string) => {
      console.log(s)
    }
    v('s')
    // 3.使用 this 必须定义成普通函数
    type Person = {
      name: string
      age: number
    }
    // this 必须声明在第一个参数,且必须叫 this
    type FnWithThis = (this: Person, gender: string) => void
    const sayHi: FnWithThis = function() {
      console.log('hi ' + this.name)
    }
    // sayHi('女') 这样调用报错,因为没有 this
    const p: Person = {
      name: 'rourou',
      age: 18
    }
    sayHi.call(p, '女') // this 为 p 对象
    

五、使用 TS 来描述其他对象

  • Date、RegExp、Map、WeakMap、Set、WeakSet
    // Date
    const d: Date = new Date()
    // RegExp
    const reg: RegExp = new RegExp('ab+c')
    // Map
    const map: Map<string, number> = new Map()
    map.set('age', 18)
    map.get('age')
    // weakMap
    const weakMap: WeakMap<{name: string}, string> = new WeakMap()
    weakMap.set({name: 'rourou'}, '女')
    // Set
    const set: Set<number> = new Set()
    set.add(1)
    // WeakSet
    const weakSet: WeakSet<{age: number}> = new WeakSet()
    const obj = {age: 18}
    weakSet.add(obj)
    

六、any、unknown、never

  • any 代表任何类型(全集)
    const a: any = 1
    const b: any = '1'
    const c: any = {}
    const d: any = []
    const e: any = new Set()
    
  • unknown 代表不知道是什么类型(例如从接口拿到的数据)(未知集)
    const a: unknown = 1;
    (a as number).toFixed(2)
    
  • never (空集)
    注:unknown 使用要优先于 any,因为 unknown 后面可以使用断言来再次定义其类型