typescript - typescript function argument inherits from
问题描述
I have a super class, such as
class SuperClassy {
}
Which has many other classes extending it:
class SubClassy extends SuperClassy {
}
class OtherSubClass extends SuperClassy {
}
etc.
I have functions for which I want to specify the argument must be in this group of derived classes.
I don't want to have to create a union type manually, I'd rather just declare that the argument in question must inherit from SuperClassy.
Something like:
function doStuff(c: InheritsFrom<SuperClassy>) {
}
such that this will compile:
doStuff(new SubClassy()) {
}
and this will not:
doStuff(4);
-- EDIT --
Here is an example where simply requiring parameter to be SuperClassy does not work:
class SuperClassy {
id: string;
}
class SubClassy extends SuperClassy {
x: number;
}
class OtherSubClass extends SuperClassy {
y: number;
}
function doStuff(c: (c: SuperClassy) => (d: SuperClassy) => boolean) {
return 'j';
}
doStuff((c: SubClassy) => {
return (k: OtherSubClass) => {
return c.id === k.id;
}
});
Compiler throws this error:
Argument of type '(c: SubClassy) => (k: OtherSubClass) => boolean' is not assignable to parameter of type '(c: SuperClassy) => (d: SuperClassy) => boolean'.
Types of parameters 'c' and 'c' are incompatible.
Property 'x' is missing in type 'SuperClassy' but required in type 'SubClassy'.
解决方案
How about using generics? (I added default values to the class definitions to suppress compiler errors.
class SuperClassy {
id: string = "id";
}
class SubClassy extends SuperClassy {
x: number = 0;
}
class OtherSubClass extends SuperClassy {
y: number = 0;
}
function doStuff<T extends SuperClassy, U extends SuperClassy>(
c: (c: T) => (d: U) => boolean
) {
return "j";
}
doStuff((c: SubClassy) => {
return (k: OtherSubClass) => {
return c.id === k.id;
};
});
推荐阅读
- python - ValueError:层模型需要 3 个输入,但它接收到 1 个输入张量。收到的输入:[
ValueError: Layer model expects 3 input(s), but it received 1 input tensors. Inputs received: [<tf.Tensor
- php - .htaccess 问题,我无法删除 .php
- python - 如何从pytube流中提取元素?
- html - Bootstrap - 如何删除此引导卡底部的多余空间?
- python-c-api - 调用 PyErr_Set*() 函数时不增加异常对象的引用计数
- assembly - 程序执行一个循环来总结输入中的所有值。如何优化 MIPS 中的循环部分?
- r - 有没有一种快速的方法来计算两个数据集之间的布雷距离?
- google-cloud-platform - 更改在 Google Cloud 上购买的承诺使用折扣的地区
- mysql - 如何使用 JSON 函数从 mysql 中的另一个数组中删除数组元素?
- node.js - 如何将 .obj 文件上传到从 expo 文档选择器中选择的 cloudinary?