使用泛型或继承哪种方式更正确?



我正试图将新的合同应用到我们的图标系统中,我们遇到了这种争论,哪种方式更正确?

(结果界面相同):
使用泛型->接口不太清楚,但一旦设置了type属性,我们就会收到自动完成和编译错误
不使用泛型->将要求开发人员为期望接收Icon的任何对象执行' as AccountIcon '(或其他类型)<标题>Inhertience例子

export interface Icon {
type: 'account' | 'img' | 'font-icon';
}
export interface AccountIcon extends Icon {
readonly type: 'account';
value: LinkIcon<LinkIconType>;
}
export interface ImgIcon extends Icon {
readonly type: 'img';
value: Icon;
}
export interface FontIcon extends Icon {
readonly type: 'font-icon';
value: string;
}
<标题>

泛型实例h1> div class="one_answers">我会做一个歧视联合。

https://basarat.gitbook.io/typescript/type-system/discriminated-unions

export interface AccountIcon {
readonly type: 'account';
value: LinkIcon<LinkIconType>;
}
export interface ImgIcon {
readonly type: 'img';
value: IconValue;
}
export interface FontIcon {
readonly type: 'font-icon';
value: string;
}
export type Icon = AccountIcon | ImgIcon | FontIcon;

这在逻辑上符合你的用例——你有多种类型的图标,但有时你可能想要在不知道特定类型的情况下使用它们。

这里的优点是typescript足够聪明,当你在条件下检查类型时,它可以判断出类型:

if (icon.type === 'img') {
// Typescript knows icon is an ImgIcon 
} else {
// Typescript knows that icon is not an ImgIcon.
}

最新更新