不,您不能,您将得到一个错误:
Interface 'B' incorrectly extends interface 'A'.
Types of property 'address' are incompatible.
Type 'number[]' is not assignable to type 'string[]'.
Type 'number' is not assignable to type 'string'.
但是您可以做的是使用Omit
继承除address
之外的所有字段
TS Playground个
interface A {
id: string;
name: string;
gender: string;
address: string[];
}
// This doesn't work
/*
interface B extends A {
address: number[];
}
*/
// This does
interface B2 extends Omit<A,"address"> {
address: number[];
}
const myInstance: B2 = {
id: "1",
name: "Foo",
gender: "male",
address: [1, 2, 3]
};
另一个有效的解决方案是拥有一个通用接口.
interface X<T = number | string> {
id: string;
name: string;
gender: string;
address: T[];
}
interface A extends X<string> {
}
interface B extends X<number> {
}
const instance: B = {
id: "1",
name: "Foo",
gender: "male",
address: [1, 2, 3]
};