Keyof for Nested Objects

Jul 22, 2025 · 1 min read · 113 Words · -Views -Comments · Programming
TypeScript 🇨🇳 阅读中文版
Read with AI

Choose an AI assistant

ChatGPT Open in a new tab with the article link and prompt
Claude Copy the prompt, then open Claude

Open Claude
Trouble reading the article?

If the prompt is missing, copy the full prompt below into your AI assistant. If the AI cannot read the article, paste the visible passage you want to discuss and add your question.

Problem

interface User {
  parent: {
    name: string;
  };

  age: number;
  name: string;
}

type Column = {
  key: keyof User;
};

const columns: Column[] = [
  {
    key: 'name'
  },
  {
    key: 'name1'
  },
  {
    key:'parent.name'
  }
];

Solution

type Paths<T> = T extends object ? { [K in keyof T]:
  `${Exclude<K, symbol>}${"" | `.${Paths<T[K]>}`}`
}[keyof T] : never

type Column = {
  key: Paths<User>;
};

In addition to writing your own Paths type, you can also use existing libraries, such as the Path type from type-fest.

Result

const columns: Column[] = [
  {
    key: 'name'
  },
  {
    key: 'parent.name' // ok
  },
    {
    key: 'parent.name1' // error
  }
];

References

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover