typescript - 基于泛型类型的可选属性
问题描述
我想根据泛型类型将属性设为可选。我尝试了以下方法:
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" };
所以想法是属性text
only 被定义为Option<'text'>
并且media
only 被定义为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;
}
}
推荐阅读
- sql-server - 如何使用 SELECT 语句中的可用值更新表
- python - 如何将剩余字符串“34defg”添加到输出python
- javascript - 在渲染我的应用程序时,如何将不同的反应片段放在一起以避免“元素类型无效错误”?
- excel - 在excel vba中循环多个值
- kotlin - 如何在许多字符串中找到为空或 null 的字符串并使代码看起来干净
- javascript - 不确定为什么图标旋转功能部分工作 Javascript
- flutter - 如何向 BottomNavigationBarItem 添加阴影
- javascript - 这在递归中叫什么?
- search - 邻域搜索在 CPLEX 中的应用
- excel - 我无法在 Microsoft Excel 中获取国家/地区的纬度和经度