dnd*_*ndr 2 typescript typescript-generics
我想根据泛型类型使属性可选。我尝试了以下方法:
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" };
Run Code Online (Sandbox Code Playgroud)
所以这个想法是属性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)
Run Code Online (Sandbox Code Playgroud)
我该如何解决这个问题?
您不能让属性的可选性依赖于接口中的泛型类型参数。但是,您可以改用类型别名和交叉点:
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" };
Run Code Online (Sandbox Code Playgroud)
尽管您可能会因受歧视的工会而过得更好 :
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;
}
}
Run Code Online (Sandbox Code Playgroud)
您可以通过工会来做到这一点:
type Option<T extends 'text' | 'audio' | 'video'> =
{
id: string;
type: T;
}
&
(
T extends 'text'
? {text: string}
: {media: T}
);
const option: Option<'text'> = { text: "test", type: "text", id: "opt1" };
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
142 次 |
| 最近记录: |