TS之数据类型(一)

99 阅读1分钟

TS 中的数据类型

nullundefinedstringnumberbooleanobjectbigIntsymbolvoidneverenumunknownany、还有自定义类型 typeinterface

对象的数据类型

思考: Object 包含哪些类型

Object 包含多种类型

    type Object = Array | Function | String | Number | Boolean | RegExp | Date| ...
    // 还包括自定义类型等

严禁使用包装类型

  • 例如
    const a: Object = 1 // 正确

不使用包装类型 NumberStringBoolean

描述普通对象

  1. 索引签名

    索引签名参数类型必须是 “string”、“number”、“symbol”或模板文本类型。

    // 索引签名
    type A= {  // 表示 key 为string,value为number的所有对象
        [k: string]: number // k 可以为任何单词
    }
  1. Record泛型
    type A = Record<string, number>

描述数组

  1. Array 泛型
  2. string[] 或 [string, number]
    type strArr = Array<string>
    type strArr2 = string[]
    type strArr3 = [18, 32]

描述函数

一般使用 () => ? 描述函数, ?仅指返回值类型

    type Fna = (x:number, y: number) => number 
    const a: Fna = () => 89; // 实现时没有传入或使用参数
    a(1, 2); // 使用时需要符合类型Fna
    
    type FnReturnVoid = () => void
    type FnReturnUndefined = () => undefined
    const f1: FnReturnVoid = () => {
    };
    const f2: FnReturnUndefined = () => {
      return undefined;
    };

关于函数中的 this

  • this 作为第一个参数,通过 . 调用或者applycallbind改变 this 指向
     type Person = {
      name: string;
      age: number;
    };

    type FnWithThis = (this: Person, name: string) => void;

    const sayHi: FnWithThis = function () {
      console.log("hi " + this.name);
    };
    sayHi.apply({ name: "张三", age: 18 }, ["jack"]);

其他对象

    // 日期
const d: Date = new Date();
// 正则
    const r: RegExp = /awd/;
    const r2: RegExp = new RegExp("awd");
    const m: Map<string, number> = new Map();
    const wm: WeakMap<{ name: "awd" }, number> = new WeakMap();
    const s: Set<number> = new Set();