typescript - 如何根据打字稿接口的条件类型有条件地定义属性
问题描述
假设我有一个在代码库中使用的现有打字稿接口
interface example<condition extends true | false = false> {
a: string;
b: string;
c: condition extends true ? string : number;
// many other properties
}
现在我想保留属性a如果条件为真,但如果条件为假,则将属性a替换为属性d,我该怎么做?
是否有任何简单的方法,例如 javascript 对象如何使用它,如下所示(虽然有语法错误)
interface example<condition extends true | false = false> {
...(condition extends true && {a: string});
...(condition extends false && {d: string});
b: string;
c: condition extends true ? string : number;
// many other properties
}
解决方案
找到了解决方案
type Example<Condition extends boolean = false> = {
b: string;
c: string;
e: string;
f: string;
g: string;
h: string;
i: string;
} & (Condition extends true ? {
a: string;
} : {
d: string;
})
无论如何可以通过使用接口来做到这一点?
推荐阅读
- azure - Azure 应用服务上的出站连接超时
- node.js - Sequelize——一种定义动态属性的方法
- node.js - Angular 8 - 无法让 httpClient POST 与 Socket.io 一起完成它的工作?
- arrays - Kotlin 按一项对两个列表进行排序
- ios - 将图像大小减小到最大 100 kb,并在 iOS 中固定尺寸为 512x512
- javascript - 从 Ruby on Rails 输出哈希数组到 chart.js
- python - 导入类时未定义 NameError DataFrame
- java - 对于 commn-service 中存在的类,微服务项目在 mvn 包中找不到类
- node.js - 将集合加入到现有的聚合查询 mongodb
- python - 什么是“一次性完成”?