[TypeScript] Query Properties with keyof and Lookup Types in TypeScript
2024-09-03 07:14:08
The keyof
operator produces a union type of all known, public property names of a given type. You can use it together with lookup types (aka indexed access types) to statically model dynamic property access in the type system.
Take away:
1. extends
2. keyof
interface Todo {
id: number;
text: string;
completed: boolean;
} const todo: Todo = {
id: ,
text: "Buy milk",
completed: false
} // K extends keyof T: K will be the unit types of 'id', 'text', 'completed'
// T[K] is the lookup tells the Typescript the correct return type
function prop<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
} type TodoId = Todo['id'];
type TodoText = Todo['text'];
type TodoCompleted = Todo['completed']; const id: TodoId = prop(todo, 'id'); // type number
const text: TodoText = prop(todo, 'text'); // type string
const completed: TodoCompleted = prop(todo, 'completed'); // type boolean
最新文章
- JavaScript 构造函数与原型链
- iOS--通讯录、蓝牙、内购、GameCenter、iCloud、Passbook等系统服务开发汇总
- php ffmpeg
- json 和 pickel 详解
- SharePoint Server 2007 简体中文下载
- vs2010 无法连接到asp.net development server
- CodeForces 489C Given Length and Sum of Digits... (贪心)
- 破解Windows Server 2003只允许3个用户远程登陆
- C# To C++ Converter Cracked ( 破解版 )
- git 学习(3) ----- 代码共享和多人协作
- 如何快速开发html5跨平台K12/幼儿交互课件、动画课件、交互游戏
- 带你了解源码中的 ThreadLocal
- confd
- go,gcvis,golang, privoxy,and git proxy
- 使用ASP.NET AJAX与Bootstrap 弹窗解决方案
- MCI 录制指定格式音频
- PBOCIC读芯片卡流程
- Rabbitmq安装及启动 MAC系统
- bzoj 1237 [SCOI2008]配对 贪心+dp
- Hibernate查询_HQL_EJBQL_QBC_QBE
热门文章
- ansible2.7学习笔记系列
- 第1节 flume:9、flume的多个agent串联(级联)
- ffmpeg解析TS流
- 关于U盘安装ubuntu-18.04安装时候出现的grub-efi-amd64-signed的问题。
- 前端基础之CSS_2
- UVALive - 6275 Joint Venture (二分)
- JSP配置即报错以及解决办法(未更新完)
- luogu3380 【模板】二逼平衡树(树套树)
- Python浅拷贝copy()与深拷贝deepcopy()区别
- 《Docker容器与容器云》读书笔记