TypeScript组合和扩展类型

361 阅读2分钟

组合类型

联合类型

联合类型与交叉类型很有关联,但是使用上却完全不同。 偶尔你会遇到这种情况,一个代码库希望传入 number或 string类型的参数。

使用联合,你可以声明一个类型是多种类型之一

例如您可以将 boolean 类型描述为 true 或 false:

type MyBool = true | false; type WindowStates = "open" | "closed" | "minimized"; type LockStates = "locked" | "unlocked"; type PositiveOddNumbersUnderTen = 1 | 3 | 5 | 7 | 9;

联合还可以处理含有不同类型的参数

function getLength(obj: string | string[]) {
  return obj.length;
}

联合类型

定义联合类型

function printId(id: number | string) {
  console.log("Your ID is: " + id);
}
// OK
printId(101);
// OK
printId("202");

使用联合类型

联合类型的使用只有在对联合的所有类型都有效的情况下才允许操作,例如,如果您有联合 string | number,则不能使用仅在 string 上可用的方法

解决办法是缩小联合,确定具体类型

例如

function printId(id: number | string) {
  if (typeof id === "string") {
    // In this branch, id is of type 'string'
    console.log(id.toUpperCase());
  } else {
    // Here, id is of type 'number'
    console.log(id);
  }
}

若是Array类型

function welcomePeople(x: string[] | string) {
  if (Array.isArray(x)) {
    // Here: 'x' is 'string[]'
    console.log("Hello, " + x.join(" and "));
  } else {
    // Here: 'x' is 'string'
    console.log("Welcome lone traveler " + x);
  }
}

当然我们也可以直接使用联合类型中的共同属性

例如

function getFirstThree(x: number[] | string) {
  return x.slice(0, 3);
}

交集类型

交集类型使用&关键符将多个类型合并成一个新的类型 交叉类型是将多个类型合并为一个类型。 这让我们可以把现有的多种类型叠加到一起成为一种类型,它包含了所需的所有类型的特性。 例如, Person & Serializable & Loggable同时是 Person  Serializable  Loggable。 就是说这个类型的对象同时拥有了这三种类型的成员。

interface Colorful{
  color:string;
}
interface Circle{
  radius:number;
}

type ColorfulCircle = Colorful&Circle

function draw(circle: Colorful & Circle) {

}

// okay
draw({ color: "blue", radius: 42 });

扩展类型

类型别名

使用type关键字来定义类型别名

我们可以创建类型别名来表示对象类型或者联合类型

type Point = {
  x:number;
  y:number;
}
function printCoord(pt:Point){
}

printCoord({ x: 100, y: 100 });
type ID = number| string

泛型类型

使用泛型来创建通用类型

interface Box<T>{
  value:T;
}
const box1: Box<number> = { value: 123 };
const box2: Box<string> = { value: 'hello' };

您可以声明自己的使用泛型的类型:

interface Backpack<Type> {
  add: (obj: Type) => void;
  get: () => Type;
}

//定义了一个实现接口的类
declare const backpack: Backpack<string>;

const object = backpack.get();

backpack.add(23);