Home > other >  add suffix to every key in object recursively
add suffix to every key in object recursively

Time:11-03

Function is minimized. It should add "blabla" to every single object key as suffix (recursively).

TS playground link

Error

Type 'any[]' is not assignable to type 'T'.
  'T' could be instantiated with an arbitrary type which could be
    unrelated to 'any[]'.
(2322)

Input

addBlabla([{ a: [{ b: 1 }] }])

Output

{
  ablabla: {
    b: number; // not a "bblabla"
  }[];
}[]

TS playground link

CodePudding user response:

TS playground: https://tsplay.dev/wQKyVm

I removed Array.isArray part because Array is also object (typeof).

CodePudding user response:

You have two errors in the type declaration and the implementation.

In the type, you map every object to the type of himself instead of AddBlabla.

type AddBlaBla<T> = T extends readonly any[]
  ? { [K in keyof T]: AddBlaBla<T[K]> }
  : T extends object
  // ? { [K in keyof T as `${Exclude<K, symbol>}blabla`]: T[K] } // replace this
  ? { [K in keyof T as `${Exclude<K, symbol>}blabla`]: AddBlaBla<T[K]> } // with this
  : T;

The implementation is here.

  • Related