Skip to main content

一个TypeScript类型复用的小技巧

· One min read
Alan

分享一个TypeScript类型复用的小技巧:

为了复用Brand类型, 一般都是这么写, 单独定义Brand类型:

type Brand = {
brandId: string,
brandName: string
}
type DealerLogItem = {
city: { cityName: string, cityId: string },
brand: Brand,
dealers: Array<Dealer>
}

const map = new Map<string, Brand>();

其实还可以这么写:

type DealerLogItem = {
city: { cityName: string, cityId: string },
brand: { brandId: string, brandName: string },
dealers: Array<Dealer>
}

const map = new Map<string, DealerLogItem["brand"]>();

这样 DealerLogItem 上的字段定义就能复用了.