基于泛型类型的可选属性
我想根据泛型类型使属性可选。我尝试了以下方法:
interface Option<T extends 'text' | 'audio' | 'video'> {
id: string;
type: T;
text: T extends 'text' ? string : undefined;
media: T extends 'audio' | 'video' ? T : undefined;
}
const option: Option<'text'> = { text: "test", type: "text", id: "opt1" };
所以这个想法是属性textonly 被定义为Option<'text'>并且media只被定义为Option<'audio' | 'video'>。
但是,ts 编译器给了我以下错误:
Property 'media' is missing in type '{ text: string; type: "text"; id: string; }'
but required in type 'Option<"text">'.ts(2741)
我该如何解决这个问题?
回答
您不能让属性的可选性依赖于接口中的泛型类型参数。但是,您可以改用类型别名和交叉点:
type Option<T extends 'text' | 'audio' | 'video'> = {
id: string;
type: T;
}
& (T extends 'text' ? { text: string } : {})
& (T extends 'audio' | 'video' ? { media: T }: {});
const option: Option<'text'> = { text: "test", type: "text", id: "opt1" };
玩
尽管您可能会因受歧视的工会而过得更好 :
type Option =
| { id: string; type: 'text'; text: string }
| { id: string; type: 'audio' | 'video'; media: 'audio' | 'video' };
const option: Extract<Option, {type: 'text' }> = { text: "test", type: "text", id: "opt1" };
function withOption(o: Option) {
switch(o.type) {
case 'text': console.log(o.text); break;
default: console.log(o.media); break;
}
}
游乐场链接