TS的笔记

keyof

返回值为联合类型(或者的关系)

1
2
3
4
5
6
7
8
interface IArticle {
  content: string;
  authorId: number;
  category: string;
}

// 'content' | 'authorId' | 'category'
type ArticleKeys = keyof IArticle;

结合 typeof 操作符获取对象的 keys

1
2
3
4
5
6
7
8
const article = {
  content: 'content',
  authorId: 123,
  category: 'misc',
};

// 'content' | 'authorId' | 'category'
type ArticleKeys = keyof typeof article;