从 TypeScript 中的接口中删除属性
使用 Omit 实用程序类型从接口中删除属性,例如 type WithoutAge = Omit<Person, ‘age’>。 Omit 实用程序类型通过从现有接口中删除指定的键来构造新类型。
interface Person {
name: string;
age: number;
address: string;
}
// ✅ Remove 'age' property from interface
type WithoutAge = Omit<Person, 'age'>;
// ✅ Remove multiple properties from interface
type WithoutAgeAndAddress = Omit<Person, 'age' | 'address'>;
// ✅ Remove property and extend interface
interface PersonWithoutAge extends Omit<Person, 'age'> {
language: string;
}
我们可以使用 Omit 实用程序类型从接口中删除一个或多个属性。
在不向其添加任何属性的情况下进行扩展和接口是没有意义的,因此声明一个类型更直观。
在第三个示例中,我们从 Person 类型中删除了 age 属性,并使用 language 属性扩展了新构造的类型。
这是上面示例的更详细版本,我们在其中创建符合新构造类型的创建对象。
interface Person {
name: string;
age: number;
address: string;
}
// ✅ Remove 'age' property from interface
type WithoutAge = Omit<Person, 'age'>;
const obj1: WithoutAge = {
name: 'Tom',
address: 'Example str 123',
};
// ✅ Remove multiple properties from interface
type WithoutAgeAndAddress = Omit<Person, 'age' | 'address'>;
const obj2: WithoutAgeAndAddress = {
name: 'Alfred',
};
// ✅ Remove property and extend interface
interface PersonWithoutAge extends Omit<Person, 'age'> {
language: string;
}
const obj3: PersonWithoutAge = {
name: 'James',
address: 'Example str 123',
language: 'English',
};
我们经常会看到在覆盖特定属性的类型时使用的 Omit 实用程序类型。
interface Person {
name: string;
age: number;
address: string;
}
// ✅ Remove property to change its type
interface PersonWithVerboseAddress extends Omit<Person, 'address'> {
address: {
country: string;
city: string;
};
}
const obj3: PersonWithVerboseAddress = {
name: 'James',
age: 30,
address: {
country: 'Chile',
city: 'Santiago',
},
};
我们从 Person 接口中删除了 address 属性,然后将其类型更改为对象。
这比将我们需要的属性从 Person 接口复制到另一个接口要好得多,因为我们仍然向代码的读者发出信号,表明这两个接口之间存在关系。
interface Person {
name: string;
age: number;
address: string;
}
// ⛔️ Error: Type {country: string; city: string} is not
// assignable to type 'string'
// Types of property 'address' are incompatible
interface PersonWithVerboseAddress extends Person {
address: {
country: string;
city: string;
};
}
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。