我想指定3种有效的图像,并且还支持IDE,以便在输入的类型无效时显示错误
<image [src]="product.image" type="detail" [alt]="product.title" [title]="product.title"></image>
如果开发人员输入type =“details”,则应显示错误
export interface ImageType {
Detail: 'detail';
Browes: 'browes';
Thumbnail: 'thumbnail';
}
export interface ProductImage {
url: string;
type: ImageType;
}
答案 0 :(得分:0)
您可以创建一个联合类型的字符串文字,以后可以将其用于有区别的联合......
type ImageType = 'detail' | 'browes' | 'thumbnail';
export interface ProductImage {
url: string;
type: ImageType;
}
如果我尝试添加未列出的类型...我收到错误。
例如,
const image: ProductImage = {
url: 'example.com',
type: 'details'
}
结果:
Type '{ url: string; type: "details"; }' is not assignable to type 'ProductImage'.
Types of property 'type' are incompatible.
Type '"details"' is not assignable to type 'ImageType'.