我想要实现的是,仅当设置了可以具有特定值的特定泛型时,我的界面中的某些键才有效.
像这样的东西
type DeviceType = "A" | "B" | "default"
interface IIconSet<DEVICE extends DeviceType> {
info: string;
download: DEVICE extends "A" ? string : never;
refresh: DEVICE extends ("A" | "B") ? string : never;
}
然而,如果我像这样使用它,显然不能正确地推断界面中应该出现什么键,因为使用了以下对象
export const icons: IIconSet<"default"> {
info: "svgString"
}
我得到的错误是:Type is missing the following properties from type IIconSet<"default">: download, refresh
.在指定IIconSet<"B">
时也会发生同样的情况(在本例中,只要添加refresh
键,我就会得到缺少download
的错误).
然而,当使用接口IIconSet<"A">
定义对象时,它工作得很好.
我试图将上述字段设置为可选,但后来,当我想要将图标集从工厂中删除时,例如将类型转换为IIconSet<"A">
,我得到了一个错误,download
可能未定义.
当传递的泛型不符合约束时,正确的解决方案是什么--排除键?