我正在尝试为ramda的evolve
函数编写一个简单的类型定义。 (https://ramdajs.com/docs/#evolve)。官方定义无法正常工作。
type Transformation<State> = {
[Key in keyof State]: (x: State[Key]) => any
}
declare function evolve
<State extends {}, Evolver extends Partial<Transformation<State>>>(evolver: Evolver, state: State):
{[Key in keyof State]: Evolver[Key] extends (...args: any[]) => {} ? ReturnType<Evolver[Key]> : State[Key]}
我试图在泛型函数中使用它:const foo = <State extends {a: string, b: string}>(state: State) => {
const test = evolve({
a: x => x,
b: x => x
}, state)
}
但我收到一个错误:Argument of type '{ a: (x: State["a"]) => State["a"]; b: (x: State["b"]) => State["b"]; }' is not assignable to parameter of type 'Partial<Transformation<State>>'.(2345)
从错误尚不清楚为什么它不可分配,所以我不知道该如何解决
最佳答案
看来发生了几件事。我能够通过在自己的类型别名中提升Evolver
使其工作,从而在尝试将其标识为第二个通用参数时也避免了索引问题。我还将一些返回类型切换为unknown
,以使ts可以在进化器对象中推断出它们。
type Transformation<T> = {
[K in keyof T]: (x: T[K]) => unknown;
};
type Evolver<State> = Partial<Transformation<State>>;
declare function evolve<State extends { [key: string]: unknown }>(
evolver: Evolver<State>,
state: State
): {
[Key in keyof State]: Evolver<State>[Key] extends (...args: any[]) => infer R
? R
: State[Key];
};
const foo = (state: { a: string; b: string }) => {
const test = evolve(
{
a: (x) => x,
b: (x) => x,
},
state
);
};
关于typescript - 'evolve'函数的类型定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64368836/