typescript - Definicija tipa za funkciju 'evolve'


Pokušavam napisati jednostavnu definiciju tipa za funkciju evolve iz ramde. (https://ramdajs.com/docs/#evolve). Službena definicija ne radi ispravno.

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

Pokušavam to koristiti u generičkoj funkciji:

const foo = <State extends {a: string, b: string}>(state: State) => {
  const test = evolve({
    a: x => x,
    b: x => x
  }, state)
}

ali dobivam pogrešku:

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)

Nije jasno iz greške zašto se ne može dodijeliti, pa ne znam kako to popraviti

Odgovor #1

Izgleda da se događalo nekoliko stvari. Uspio sam to pokrenuti tako da sam Evolver stavio u vlastiti tip alias, što također izbjegava problem s indeksom kada se pokušava identificirati kao drugi generički parametar. Također sam promijenio neke tipove povratnih vrijednosti u unknown kako bi ts mogao zaključiti ih u evolver objektu.

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

Povezani članci