Follow

TS magic

type NestedKeyOf<ObjectType extends object> = {
  [Key in keyof ObjectType & (string | number)]: ObjectType[Key] extends object
    ? `${Key}` | `${Key}.${NestedKeyOf<ObjectType[Key]>}`
    : `${Key}`;
}[keyof ObjectType & (string | number)];

const obj = {
  a: 1,
  b: {
    c: 2,
    d: [1, 2, 3],
  },
};

const test = <T extends object>(obj: T, path: NestedKeyOf<T>) => {
  console.log(obj, path);
};


test(obj, 'b.d.length');
· · Web · 0 · 0 · 0
Sign in to participate in the conversation
小森林

每个人都有属于自己的一片森林,也许我们从来不曾走过,但它一直在那里,总会在那里。迷失的人迷失了,相逢的人会再相逢。愿这里,成为属于你的小森林。