TypeScript:如何扩展这种相似的类型?
TypeScript: How can I extend this type that is similar?
如何将 IUnitedStatesAddress
扩展到 IUnitedStatesWithTerritoryAddress
而不重复自己?唯一的区别是 IUnitedStatesWithTerritoryAddress
在 state
字段中添加了 TUnitedStatesTerritoryAbbreviation
。
// TypeScript Type: United States Address
export interface IUnitedStatesAddress {
apartmentSuite: string;
street: string;
city: string;
state: TUnitedStatesStateAbbreviation;
zipCode: string;
county: TUnitedStatesCounty;
country: string;
}
// TypeScript Type: United States With Territory Address
export interface IUnitedStatesWithTerritoryAddress {
apartmentSuite: string;
street: string;
city: string;
state: TUnitedStatesStateAbbreviation | TUnitedStatesTerritoryAbbreviation;
zipCode: string;
county: TUnitedStatesCounty;
country: string;
}
我很确定的一件事是你可以有一个基本接口(不导出)并用你的两个案例扩展它:
interface IUnitedStates {
apartmentSuite: string;
street: string;
city: string;
zipCode: string;
county: TUnitedStatesCounty;
country: string;
}
export interface IUnitedStatesAddress extends IUnitedStates {
state: TUnitedStatesStateAbbreviation;
}
export interface IUnitedStatesWithTerritoryAddress extends IUnitedStates {
state: TUnitedStatesStateAbbreviation | TUnitedStatesTerritoryAbbreviation;
}
如何将 IUnitedStatesAddress
扩展到 IUnitedStatesWithTerritoryAddress
而不重复自己?唯一的区别是 IUnitedStatesWithTerritoryAddress
在 state
字段中添加了 TUnitedStatesTerritoryAbbreviation
。
// TypeScript Type: United States Address
export interface IUnitedStatesAddress {
apartmentSuite: string;
street: string;
city: string;
state: TUnitedStatesStateAbbreviation;
zipCode: string;
county: TUnitedStatesCounty;
country: string;
}
// TypeScript Type: United States With Territory Address
export interface IUnitedStatesWithTerritoryAddress {
apartmentSuite: string;
street: string;
city: string;
state: TUnitedStatesStateAbbreviation | TUnitedStatesTerritoryAbbreviation;
zipCode: string;
county: TUnitedStatesCounty;
country: string;
}
我很确定的一件事是你可以有一个基本接口(不导出)并用你的两个案例扩展它:
interface IUnitedStates {
apartmentSuite: string;
street: string;
city: string;
zipCode: string;
county: TUnitedStatesCounty;
country: string;
}
export interface IUnitedStatesAddress extends IUnitedStates {
state: TUnitedStatesStateAbbreviation;
}
export interface IUnitedStatesWithTerritoryAddress extends IUnitedStates {
state: TUnitedStatesStateAbbreviation | TUnitedStatesTerritoryAbbreviation;
}