Typescript之keyof和typeof的作用
关于keyof和typeof的个人理解,有不妥之处,欢迎指正:
最近在学习TS的类型体操,发现还是要理论和实战结合,理论这一块就不用说了,可以看TS的官方文档,了解一些基本的概念和用法。实战的话可以在这个网站上练习(https://github.com/type-challenges/type-challenges/blob/main/README.zh-CN.md)
1、keyof的作用
作用:用来获取接口,对象,类等的所有属性名组成的联合类型。
获取接口的属性的联合类型:
type person = { name: string, age: number, }; type p = keyof person; // a = name | age interface Animal { name: string, sex: string, } type animal = keyof Animal; // animal = name | sex
获取对象属性的联合类型:
这里需要借助typeof先获取对象的类型
const info = { name: 'tom', age: 12, sex: 'man' } // 第一步利用typeof先获取对象的类型 type t = typeof info; /**上面的代码输出:type t = { name: string; age: number; sex: string; } **/ // 第二步利用keyof获取类型t的属性组成联合类型 type c = keyof t; // c = name | age | sex //上面的两步可以合并成 type c = keyof typeof info;
获取类的属性组成的联合类型:
class Demo { name!: string; age!: number constructor() { } init() {} } type demo = keyof Demo; // demo = name | age | init
2、typeof的作用
作用:根据已有的值,获取对应值的类型
获取值为数组的类型:
const arr = [1,2,3,4]; type arr1 = typeof arr // arr1 = number[]
获取值为对象的类型:
const info = { name: 'tom', age: 12, sex: 'man' } type t = typeof info; /** 输出: type t = { name: string; age: number; sex: string; } **/
分类:
Typescript笔记
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
2020-09-07 Angular2及以上版本的多语言问题