Generic for extending value of object when object can be null
04:32 25 Aug 2026

I have an object of this form:

{
  dataErrors: {
    error?: readonly string[] | undefined;
  } | null;
};

I need to add a value to the dataErrors error type if it exists; otherwise, I have to create the dataErrors object or add the error key. How do I write a generic for this? I have the following function, but this does not work:

type GetValue<
  O extends {[_key in Key]: readonly string[] | undefined} | null,
  Key extends string
> = O extends null 
      ? {[K in Key]: readonly string[]} 
      : Key extends keyof O ?
        O[Key] extends undefined 
          ? readonly string[] 
          : O[Key] 
        : readonly string[];

function addDataErrorValue<
  P extends {dataErrors: {[key in K]?: readonly string[] | undefined} | null,
  K extends string,
  M extends string,
>(
  payload: P, key: K, error: {message: M},
) {
  const dataErrors = payload.dataErrors ?? {} as typeof payload['dataErrors'];
  return {
    ...payload,
    dataErrors: {
      ...dataErrors,
      [key]: [
        ...dataErrors?.[key] ? dataErrors[key] : [],
        error.message,
      ],
    },
  } as P & {
    dataErrors: P['dataErrors'] & {
      [key in K]: P extends null ? null : [...GetValue, ...[M]]
    }
  };
}

I get the following errors (where the first error is probably a result of the second error):

TS2574: A rest element type must be an array type.

TS2344: Type P["dataErrors"] does not satisfy the constraint `{ [_key in K]: readonly string[] | undefined; } | null`

typescript