typescript - 将 intersect 类型封装到接口中
问题描述
我看到自己到处都在写以下内容:
product: Product & { id: string; };
如何编写接口,以便我可以编写
product: WithId<Product>;
我试过这样的东西,但编译器不喜欢从泛型扩展:
export interface WithId<T> extends T {
id: string;
}
解决方案
您可以通过抽象来抽象构造& {id: string}
export type WithId<T> = T & { id: string }
type Example = WithId<{ a: number }> // {a: number, id: string}
const example: Example = {a: 1, id: 'id'}
PS。{ [K in keyof T]: T[keyof T] }
和它本身没什么不同T
,所以多余。
推荐阅读
- python - 希望为每个用户 ID 创建纵向数据,但我不确定如何填充没有值的月份
- c# - 如何删除所有与模式不匹配的符号
- java - JVM 上的多个 -XX 命令行选项
- rest - 在 ZF3 中定义具有多个参数的 API 路由
- github - Github 页面不能包含在 Shiny 应用中?
- r - 从 data.frame/table 中的行创建环境变量
- python - 抓取所有页面 url 的 Python 脚本
- multithreading - 如何在 Qml/C++ 中实现繁忙指标?
- xpath - 无法使用路径提取器从响应中提取 xml 值
- curl - curl:(77)错误设置证书验证位置: