在TypeScript中,如果父接口中定义了一个属性,子接口中默认会继承这个属性。如果子接口中不希望包含父接口中的某个属性,有以下几个方法。
- 通过在子接口中声明一个同名属性来覆盖父接口中的属性。
interface ParentInterface {
requiredProperty: string;
optionalProperty: any; // 可以是任意类型
}
interface ChildInterface extends ParentInterface {
requiredProperty: string;
optionalProperty?: any; // 重写 optionalProperty 属性
}
- 使用类型断言:在子接口中使用类型断言来显式地声明该属性不存在。
interface ParentInterface {
requiredProperty: string;
}
interface ChildInterface extends ParentInterface {
// 通过类型断言来声明该属性不存在
requiredProperty: never;
}
- 使用类型别名
interface ParentInterface {
requiredProperty: string;
anotherProperty: any; // 必传属性
}
type ChildInterface = {
requiredProperty: string;
};
接口或联合类型可以用来扩展,type怎么扩展
type Person = {firstName: string;};
type Employee = Person & {position: string; office: string;};
let employee: Employee = {firstName: 'John', position: 'Manager', office: 'New York'};
这个联合类型定义了Employee
是一个Person
类型和另一个类型。这表明employee
变量必须包含Person
类型的所有属性和方法,并拥有position
和office
属性。