2 种在 TypeScript 中扩展类型的方法

这篇简短而直接的文章向您展示了在 TypeScript 中扩展类型的几种不同方法。废话不多说,看代码吧。

使用“extends”关键字

例子:

type TypeOne = {
  a: string;
  b: number;
};

type TypeTwo = {
  c: string;
  d: string;
};

// extend TypeOne
interface InterfaceOne extends TypeOne {
  e: string;
  f: number;
}

const x: InterfaceOne = {
  a: 'KindaCode.com',
  b: 1,
  e: 'e',
  f: 2,
};

// you can also extend multiple types at once
interface InterfaceTwo extends TypeOne, TypeTwo {
  g: string;
}

const y: InterfaceTwo = {
  a: 'a',
  b: 1,
  c: 'c',
  d: 'd',
  g: 'Welcome to KindaCode.com',
};

使用“&”运算符

例子:

type TypeA = {
    a1: string;
    a2: string;
}

type TypeB = {
    b1: string;
    b2: number;
}

// Extend TypeA
type TypeAExtended = TypeA & {
    a3: string;
    a4: number;
}

// Extend both TypeA and TypeB at the same time
type TypeC = TypeA & TypeB & {
    c1: string;
    c2: number;
    c3: boolean;
}