Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
带继承的Typescript泛型数组_Typescript_Generics_Typescript Generics - Fatal编程技术网

带继承的Typescript泛型数组

带继承的Typescript泛型数组,typescript,generics,typescript-generics,Typescript,Generics,Typescript Generics,我试图在typescript中创建一个数组,以包含接受不同类型但都从基类继承的不同函数。 像这样: 然后像这样使用它 funcs[0]({name: "ASda", bb: "b_value"}) // error 'cc' is missing in type '{ name: string; bb: string; }' funcs[1]({name: "ASda", cc: "c_value"}) // err

我试图在typescript中创建一个数组,以包含接受不同类型但都从基类继承的不同函数。 像这样:

然后像这样使用它

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; }'

您没有为函数数组
funcs
指定任何类型。使用动态类型,数组签名的定义如下:
const funcs:(((param:B)=>void)|((param:C)=>void))[]

在这种情况下,编译器不知道您实际使用的函数的签名。根据上述签名,您必须提供涵盖所有可能情况的数据:类型
B
C
,导致您看到的错误

您可以通过如下方式定义函数数组的类型来实现

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
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