一、这种通用类型:
type MapToFunctions<T> = {
[K in keyof T]?: (x: T[K]) => void;
};
在本案中,它进行罚款:
type T1 = { a: string };
const fnmap1: MapToFunctions<T1> = {
a: (x: string) => {
console.log(x);
},
}
我甚至可以排除<代码>x的类型,而原型则可以正确地推断出它有线。
但是,如果在作为参数使用的类型上添加一个指数签名,那么它就不再工作:
type T2 = {
a: string;
[key: string]: unknown;
}
const fnmap2: MapToFunctions<T2> = {
a: (x: string) => {
console.log(x);
},
}
Type { a: (x: string) => void; } is not assignable to type MapToFunctions<T2> .
Property a is incompatible with index signature.
Type (x: string) => void is not assignable to type (x: unknown) => void .
Types of parameters x and x are incompatible.
Type unknown is not assignable to type string .ts(2322)
Why does this error happen? It seems pretty obvious that property a
should have type (x: string) => void
. In fact, TypeScript seems to agree; if I leave out the type annotation for argument x
, TypeScript infers that it is a string... but then still gives the same error!