简体   繁体   English

TypeScript:如何扩展这种类似的类型?

[英]TypeScript: How can I extend this type that is similar?

How can I extend the IUnitedStatesAddress to IUnitedStatesWithTerritoryAddress without repeating myself?如何在不重复自己的情况下将IUnitedStatesAddress扩展到IUnitedStatesWithTerritoryAddress The only difference is that IUnitedStatesWithTerritoryAddress has TUnitedStatesTerritoryAbbreviation added to the state field.唯一的区别是IUnitedStatesWithTerritoryAddressTUnitedStatesTerritoryAbbreviation添加到state字段。

// 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;
}

One thing I'm pretty sure of is that you can have a base interface (not to be exported) and extend it with your two cases:我非常确定的一件事是,您可以拥有一个基本接口(不可导出)并使用您的两种情况对其进行扩展:

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM