我有一个类型MyMap,有2个不同的键,它采取一个数组的回调与不同的签名.
type MyMap = {
type1: (() => void)[]
type2: ((data: string) => void)[]
}
我想创建一个接受键和回调的泛型函数,并将其添加到MyMap类型的对象中.
const map: MyMap = { type1: [], type2: [] };
function addToMap<T extends keyof MyMap>(k: T, cb: MyMap[T][number]): void {
map[k].push(cb);
}
TypeScript向我展示了当我try 在数组中推送回调时的错误:
Argument of type '(() => void) | ((data: string) => void)' is not assignable to parameter of type '() => void'.
Type '(data: string) => void' is not assignable to type '() => void'.
Target signature provides too few arguments. Expected 1 or more, but got 0.(2345)
有没有一种方法可以让TypeScript明白我提供的回调是正确的?