首页 > 解决方案 > 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; }'

TS playground

标签: typescriptgenericstypescript-generics

解决方案


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

推荐阅读