radash icon indicating copy to clipboard operation
radash copied to clipboard

Typing on assign allowing for partials

Open jessielaf opened this issue 1 year ago • 1 comments

Hi,

I want to use assign to overwrite some values. However, because the overwrite in the assign function is the same as the first parameter, the second parameter cannot be partial. For example:

type Person = {
  firstName: string;
  lastName: string;
};

const person: Person = {
  firstName: "John",
  lastName: "Doe",
};

const person2 = rAssign(person, { firstName: "Jane" });

This gives the following error:

Argument of type '{ lastName: string; }' is not assignable to parameter of type 'Person'.

I now fixed this locally using the following:

import { assign as rAssign } from "radash";

// Gotten from https://stackoverflow.com/questions/41980195/recursive-partialt-in-typescript
type RecursivePartial<T> = {
  [P in keyof T]?: T[P] extends (infer U)[]
    ? RecursivePartial<U>[]
    : T[P] extends object | undefined
      ? RecursivePartial<T[P]>
      : T[P];
};

type newAssign = <X extends Record<string | number | symbol, any>>(
  initial: X,
  override: RecursivePartial<X>,
) => X;
export const assign = rAssign as newAssign;

However, it would be nice if this was baked into the library. I don't know if this should be another function called partialAssign, but I think the current assign function does have its limitations.

jessielaf avatar Aug 28 '24 10:08 jessielaf

@jessielaf I would recommend you to take a look at Radashi(https://github.com/radashi-org/radashi/issues/168) where we fixed this problem.

image

MarlonPassos-git avatar Sep 07 '24 20:09 MarlonPassos-git