基础类型

  1. let a: string
  2. let a: number
  3. let a: boolean

数组

  1. let a: number[]
  2. let a: Array<number>

any

  1. let a: any

函数

  1. function a (name: string): number {}

对象

  1. let pos: {x: number,y?: number}

联合类型

  1. let a: string | number

类型别名

  1. type Position = {
  2. x: number,
  3. y?: number
  4. }
  5. type Id = string | number

接口

  1. interface Person {
  2. name: string,
  3. age?: number
  4. }

类型与接口的不同

  1. 接口扩展
  2. interface Person {
  3. name: string
  4. }
  5. interface Student extends Person {
  6. age: number
  7. }
  8. 类型扩展
  9. type Person = {
  10. name: string
  11. }
  12. type Student = Person & {
  13. age: number
  14. }
  15. 接口修改,创建后可以直接修改
  16. interface Person {
  17. name: string
  18. }
  19. interface Person {
  20. age: number
  21. }
  22. 类型修改,创建后不能修改
  23. type Person = {
  24. name: string
  25. }
  26. type Person = {
  27. age: number 报错
  28. }

断言

  1. const cnavas = document.getElementById('canvas') as HTMLCanvasElement
  2. tsx中会引起混淆,推荐用第一种
  3. const cnavas = <HTMLCanvasElement>document.getElementById('canvas')

文字类型

  1. let s: 'hello'
  2. s = 'world' 报错
  3. 或者直接用const
  4. 用处
  5. type Direction = "left" | "right" | "center"
  6. let a: Direction = 'cneter' 因为拼写不对,报错
  7. 数字类型
  8. type Val = 0 | 1
  9. 跟其他类型合并
  10. interface Options {
  11. width: number;
  12. }
  13. function configure(x: Options | "auto") {
  14. // ...
  15. }
  16. configure({ width: 100 });
  17. configure("auto");
  18. configure("automatic"); 报错

自动推断

  1. let o = {
  2. name: '李狗蛋'
  3. }
  4. o.name = 11 报错
  1. const req = { url: "https://example.com", method: "GET" }; 因为在定义对象时,method属性被自动推断为string
  2. handleRequest(req.url, req.method); 报错 string 不能赋值给 "GET" | "POST"
  3. handleRequest(req.url, "GET");
  4. function handleRequest (url:string, method: "GET" | "POST"): void {}
  1. // Change 1:
  2. const req = { url: "https://example.com", method: "GET" as "GET" };
  3. // Change 2
  4. handleRequest(req.url, req.method as "GET");
  1. const req = { url: "https://example.com", method: "GET" } as const;
  2. handleRequest(req.url, req.method);

null undefined

  1. strictNullChecks off
  2. null undefined 可以赋值给任意类型
  3. strictNullChecks on (推荐打开)
  4. 只能赋值给他自己的类型
  1. 使用 ! 可以告诉ts该值不为空或未定义
  2. function liveDangerously(x: number | null) {
  3. console.log(x!.toFixed());
  4. }

不常见的类型

  1. let one: bigint = BigInt(1)
  2. const a = Symbol('name')