Typescript记录

140 阅读2分钟

交叉类型

交叉类型就是多个类型,通过 & 类型运算符,合并成一个类型。

理解为+,a+b,约等于extends,会合并两种类型

interface ErrorHandling {
  success: boolean;
  error?: { message: string };
}

interface ArtistsData {
  artists: { name: string }[];
}

const handleArtistsResponse = (response: ArtistsData & ErrorHandling) => {
  if (response.error) {
    console.error(response.error.message);
    return;
  }

  console.log(response.artists);
};

联合类型

联合类型实际上是通过操作符 |组合成一个复合类型。可以是该复合类型中任意一个类型。

type myType = string | number

复杂类型时,理解为-,a-b,取ab的共有类型

映射类型

自带函数,将对象类型处理为新的对象类型

可选属性 Partial

Partial<T>可以将类型T中所有属性变为可选属性

interface Person {
  name: string;
  age: number;
  gender: 'male' | 'female';
}

type PartialPerson = Partial<Person>;

// 等价于
// interface PartialPerson {
//   name?: string;
//   age?: number;
//   gender?: 'male' | 'female';
// }

只读属性 Readonly

Readonly<T>可以将类型<T>中所有属性变为只读属性

interface Person {
  name: string;
  age: number;
  gender: 'male' | 'female';
}

type ReadonlyPerson = Readonly<Person>;

// 等价于
// interface ReadonlyPerson {
//   readonly name: string;
//   readonly age: number;
//   readonly gender: 'male' | 'female';
// }

规定类型的键和值 Record

Record<K,T>可以规定一个属性的键和值的类型

type Dictionary<T> = Record<string, T>;

// 此时规定dict的键为string类型,值为number类型
let dict: Dictionary<number> = {
  foo: 123,
  bar: 456,
};

查找并返回新类型 Pick

Pick<T,K>:从类型T中选择指定的属性K(可通过|多选),并返回一个新对象类型

interface Person {
  name: string;
  age: number;
  gender: 'male' | 'female';
}

type PersonNameAndAge = Pick<Person, 'name' | 'age'>;

// 等价于
// interface PersonNameAndAge {
//   name: string;
//   age: number;
// }

泛型

接口使用泛型

interface Box<T> { value: T; }
let box: Box<number> = { value: 123 };
console.log(box); // 输出:{ value: 123 }
let box2: Box<string> = { value: "hello" }; 
console.log(box2); // 输出:{ value: 'hello' }

内置泛型

Readonly

void和never

void用于函数返回时,代表函数不会返回。用于变量时,代表变量只能是null或undefined

never用于函数返回时,代表函数没有返回并且可以抛错。用于变量时,代表永远不会发生改变(我认为是永远不会出现)的情况。

在 TS 中, null 和 undefined 是任何类型的有效值,所以无法正确地检测它们是否被错误地使用。于是 TS 引入了 --strictNullChecks 这一种检查模式。 由于引入了 --strictNullChecks ,在这一模式下,null 和 undefined 能被检测到。所以 TS 需要一种新的底部类型( bottom type )。所以就引入了 never。