【发布时间】:2019-02-22 15:17:45
【问题描述】:
在我的项目中,我有一个充当文件通用类型的类。根据我们正在处理的文件类型,它应该公开其他属性。
我尝试使用默认为never 的条件类型来“隐藏”该属性。但是,当我尝试使用该类时,类型检查器抱怨我缺少被推断为never 类型的属性。当然,我不能分配它,所以我留下了一个无法创建的对象。
错误一直发生在这段代码的底部:
// just for convenience
type MP4OptionsT = {
codec?: 'h264',
profile: 'baseline' | 'main' | 'high',
bitrate: number,
};
// this is the class in question
class MediaFile<Format extends 'mp4' | 'png'> {
public path: string;
public format: Format extends 'mp4' ? 'mp4' : Format extends 'png' ? 'png' : never; // once the generic type argument is set, this can only be a specific string literal
// this should not have to be assigned if generic type argument is 'png'
public mp4Options: Format extends 'mp4' ? MP4OptionsT : never;
constructor(opts: {
path: string,
format: Format extends 'mp4' ? 'mp4' : Format extends 'png' ? 'png' : never;
// this should not have to be assigned if generic type argument is 'png' - however it demands to be assigned
mp4Options: Format extends 'mp4' ? MP4OptionsT : never,
}) {
this.path = opts.path;
this.format = opts.format;
this.mp4Options = opts.mp4Options;
}
}
// this is OK
const mp4File = new MediaFile<'mp4'>({
path: '/some/file/somewhere.mp4',
format: 'mp4',
mp4Options: {
profile: 'high',
bitrate: 1000,
}
});
// the type checker complains about this: "Property mp4Otions is missing in type {...}".
// if I explicitly include mp4Options, the type checker notes that "Type any is not assignable to Type never" - which makes sense, but precludes this class from ever being instantiated.
const pngFile = new MediaFile<'png'>({
path: '/some/file/somewhere.png',
format: 'png', // since there is exactly one option for this, it would be nice if it were implicitly set...
});
根据我对此页面http://www.typescriptlang.org/docs/handbook/advanced-types.html 的条件类型部分的理解,似乎mp4Options 一旦被评估为never 类型,就应该能够“不存在”。
作为 ab 实验,我也尝试让它回退到未定义。如果我手动分配mp4Options: undefined,这会起作用,否则类型检查器仍然会抱怨缺少属性。我认为绝对不应该是这种情况,因为我们可以省略开箱即用的 undefined 属性(没有条件类型)。
是否有解决方法或不那么复杂的方法?还是我的代码中有错误?
【问题讨论】:
标签: typescript type-inference conditional-types