typescript - 使用泛型扩展 Type1 或 Type2
问题描述
有没有办法在 TypeScript 中type1
或type2
在 TypeScript 中扩展泛型 T?
例如,我有以下内容:
interface Edible { }
interface Fruit extends Edible {
isFruity: boolean
}
interface Veggie extends Edible {
isHealthy: boolean;
}
interface Dairy extends Edible {
isHighProtein: boolean;
}
interface Apple extends Fruit {
nice: boolean;
sweet: boolean;
}
// and so on so forth...
现在我想要一个函数来接受 aFruit
或的东西,Veggie
我该如何实现呢?这是表达“扩展Fruit
或Veggie
”的正确方式吗?
function yum<T extends Fruit | Veggie>(thing: T) {
//...
if ("isFruity" in thing) {
thing.isFruity; // Error: Property 'isFruity' does not exist on type 'T'.
}
}
此外,如何进一步缩小类型Apple
,例如?
function yum<T extends Fruit | Veggie>(thing: T) {
//...
if ("isFruity" in thing) {
thing.isFruity; // Error: Property 'isFruity' does not exist on type 'T'.
if ("sweet" in thing) {
console.log("this is an apple!");
thing.sweet; // Error: Property 'sweet' does not exist on type 'T'.
}
}
}
解决方案
推荐阅读
- tensorflow - 如何编写 keras lambda 层以将“矢量”输入层转换为带有 keras 后端的“图像”层?
- java - 如何将 JTextField 文本添加到 String[] 数组
- java - 有没有更有效的方法可以处理我需要检查响应的 10 分钟以上的系统延迟
- python - np.nan 和 None 的行为有何不同?
- python - 在 googlemaps 包中找不到 GoogleMaps
- python - 如何按列名标记行
- python - 基于具有共同元素的列表中的元素组合
- javascript - React useContext throws Invalid hook call error
- c++ - 在模板化静态成员初始化中添加和不添加“typename”都会出错
- google-sheets - merge columns over multiple rows with a common column