typescript - Typescript generics array with inheritance
问题描述
Im trying to create an array in typescript to contain different functions that accept different types but they all inherit from a base class. like so:
interface A {
name: string;
}
interface B extends A{
bb: string;
}
interface C extends A{
cc: string;
}
const funcs = [
(param: B) => {
},
(param: C) => {
},
]
and then use it like so
funcs[0]({name: "ASda", bb: "b_value"}) // error 'cc' is missing in type '{ name: string; bb: string; }'
funcs[1]({name: "ASda", cc: "c_value"}) // error 'bb' is missing in type '{ name: string; cc: string; }'
解决方案
You didn't specified any type for your array of function funcs
. With dynamic typing, your array signature is defined like so : const funcs: (((param: B) => void) | ((param: C) => void))[]
In that case, compiler doesn't know the signature of the function you actually use. According the above signature, you have to provide data covering all possible case : type B
and C
resulting in the error you see.
You could make it work by defining the type of your array of functions like so
const funcs: Function[] = [
(param: B) => {
},
(param: C) => {
},
]
funcs[0]({name: "ASda", bb: "b_value"}) //No error
funcs[1]({name: "ASda", cc: "c_value"}) //No error
推荐阅读
- ruby-on-rails - 如何授予通过 Rails 控制台执行的 Ruby 脚本对 Digital Ocean 的写入权限?
- json - 在哪里/如何获得前 10,000 条维基百科文章标题,按页面浏览量?
- postgresql - 在测试环境中加载 structure.sql 需要 Rails 5 中的哪些 rake 任务?
- javascript - 设置 minDate 以防止在开始日期之前选择结束日期
- ansible - ansible auto 用“
" - redis - 从 redis 排序集中按排名检索项目(并处理可以共享排名的项目)
- python - JSON 到 Python 数据框的转换
- r - 仅舍入数字输入,否则在 R 中跳过
- r - R ggplot 在没有切割数据的情况下设置 ymax 但不设置 ymin
- jquery - 切换时使菜单功能区与菜单一起向下和向上滑动