Angular 10:如何声明包含两种子模型的列表结构?
在TypeScript中声明包含两种模型的列表结构
当然不用把asset设成any啦!TypeScript有好几种类型安全的方式来实现你要的效果,下面给你拆解几种常用方案:
方案1:直接使用联合类型
这是最直接的写法,你可以把asset的类型指定为AssetFull | AssetLink,这样TypeScript就明确知道这个字段可以是两种模型中的任意一种:
import { AssetFull, AssetLink } from './asset.model' export class Roster { public title: string; public manifest: string; public assets: { quantity: number, asset: AssetFull | AssetLink }[]; }
方案2:定义类型别名(适合复用场景)
如果这个包含quantity和asset的结构在其他地方也会用到,你可以给它起个类型别名,让代码更整洁易读:
import { AssetFull, AssetLink } from './asset.model' type AssetEntry = { quantity: number; asset: AssetFull | AssetLink; } export class Roster { public title: string; public manifest: string; public assets: AssetEntry[]; }
方案3:使用接口(更贴合面向对象风格)
如果你习惯用接口来定义数据结构,也可以采用这种写法:
import { AssetFull, AssetLink } from './asset.model' interface AssetEntry { quantity: number; asset: AssetFull | AssetLink; } export class Roster { public title: string; public manifest: string; public assets: AssetEntry[]; }
额外小提示
之后在使用assets数组里的asset字段时,TypeScript会要求你做类型收窄(比如用instanceof、自定义类型守卫)来区分AssetFull和AssetLink,这样能全程保证类型安全,避免不必要的错误。
内容的提问来源于stack exchange,提问作者jugglervr
相关产品推荐
相关产品推荐

