typescript - 扩展两个接口中的任何一个并添加一些属性的接口?
问题描述
Action
应该有属性children
和。size?
variant?
Action
也应该实现Button
或Link
。
我怎样才能做到这一点?
这是我最好的尝试
interface Button {
action: () => void;
href?: never;
}
interface Link {
href: string;
action?: never;
}
interface Action extends Button | Link {
children: string;
size?: 'large' | 'small';
variant?: 'secondary';
}
错误:
[tslint] Forbidden bitwise operation
我真正的功能要求是我想创建一个类型或接口,它有一些道具加上action
or href
,但不是两者都有action
and href
。
解决方案
不幸的是,接口不能扩展联合类型。您可以改用交集类型:
interface Button {
action: () => void;
href?: never;
}
interface Link {
href: string;
action?: never;
}
type Action = (Button | Link) & {
children: string;
size?: 'large' | 'small';
variant?: 'secondary';
}
let a: Action = {
href: "",
children: "",
size: "large"
}
let a2: Action = {
action: () => { },
children: "",
size: "large"
}
let a3: Action = { // error
href: ""
action: () => { },
children: "",
size: "large"
}
推荐阅读
- c++ - 如何判断 C++ 应用程序存在磁盘 I/O 瓶颈?
- kubernetes - Ignite 集群上的阻塞线程
- reactjs - 如何使用反应获取单选按钮的选中值
- javascript - 仅在第一条记录中隐藏按钮 - laravel
- recaptcha - reCaptcha v3 不会阻止垃圾邮件
- php - Laravel:附加需要后跟加载?
- javascript - 在表格中添加更多行时使用js重新排序表格
- java - 简化 Gson 反序列化以在 JSON 数组中添加和删除属性
- assembly - 8086 DOS 或 BIOS 功能休眠不到 1 秒,比如 0.75 秒?
- jinja2 - 如何使用 Jinja for 循环连接字符串?