在 TypeScript 中扩展不包含属性的接口

使用 Omit 实用程序类型来扩展不包含属性的接口,例如 type WithoutTasks = Omit<Employee, 'tasks'>;。 Omit 实用程序类型通过从提供的类型中选取属性并删除指定的键来构造一个新类型。

interface Employee {
  id: number;
  name: string;
  salary: number;
  tasks: string[];
}

// ✅ 1. Exclude 1 property
// 👇️ type WithoutTasks = {
//     id: number;
//     name: string;
//     salary: number;
// }
type WithoutTasks = Omit<Employee, 'tasks'>;

// --------------------------------------------------------

// ✅ 2. Exclude multiple properties
// 👇️ type WithoutIdAndTasks = {
//     name: string;
//     salary: number;
// }
type WithoutIdAndTasks = Omit<Employee, 'id' | 'tasks'>;

// --------------------------------------------------------

// ✅ 3. Exclude property and then add more properties
interface WithAddedProps extends Omit<Employee, 'tasks'> {
  country: string;
}

const example3: WithAddedProps = {
  id: 1,
  name: 'Tom',
  country: 'Germany',
  salary: 100,
};

我们使用 Omit 实用程序类型根据提供的类型构造一个新类型,并删除了指定的键。

interface Employee {
  id: number;
  name: string;
  salary: number;
  tasks: string[];
}

type WithoutTasks = Omit<Employee, 'tasks'>;

const example1: WithoutTasks = {
  id: 1,
  name: 'Alice',
  salary: 100,
};

第一个示例创建了一个新类型,它具有 Employee 类型中的所有属性,不包括 tasks 属性。

如果需要排除多个属性,可以将字符串文字的并集传递给 Omit 实用程序类型。

interface Employee {
  id: number;
  name: string;
  salary: number;
  tasks: string[];
}

type WithoutIdAndTasks = Omit<Employee, 'id' | 'tasks'>;

const example2: WithoutIdAndTasks = {
  name: 'Bob',
  salary: 100,
};

传递字符串文字的并集时,请确保使用竖线 | 分隔要排除的属性名称。 而不是逗号或任何其他分隔符。

如果我们想排除一些属性并添加更多属性,也可以使用这种方法。

interface Employee {
  id: number;
  name: string;
  salary: number;
  tasks: string[];
}

// ✅ If you need to exclude some and then add more properties
interface WithAddedProps extends Omit<Employee, 'tasks'> {
  country: string;
}

const example3: WithAddedProps = {
  id: 1,
  name: 'Tom',
  country: 'Germany',
  salary: 100,
};

country 属性仅存在于 WithAddedProps 类型中,而 tasks 属性仅存在于 Employee 类型中。

如果我们需要更改接口上特定属性的类型,可以使用相同的方法。

interface Employee {
  id: number;
  name: string;
  salary: number;
  tasks: string[];
}

interface WithAddedProps extends Omit<Employee, 'tasks'> {
  tasks: number[]; // 👈️ change type
}

const example3: WithAddedProps = {
  id: 1,
  name: 'Tom',
  salary: 100,
  tasks: [1, 2, 3],
};

我们在扩展接口时排除了 tasks 属性,然后将其类型更改为 number[]

如果直接从 Employee 接口扩展,这是不可能的,因为类型 number[] 不能分配给类型 string[]