[TypeScript] Find common props between two types, keyword Extract
typescript Find two between Common types keyword Props
2023-09-14 09:00:45 时间
For example we have two types, we want to find the shared props in both:
interface UserBase { email: string image: string | null username: string } interface UserProfile { id: string email: string image: string | null isAdmin: boolean username: string reviews: string[] }
We can use 'Extract'
type SharedUserKeys = Extract<keyof UserBase, keyof UserProfile> // 'email' | 'image' | 'username'
Convert our union string back into an object type with the shared properties and their corresponding value types.
'in' keyword, means loop over all the key in the union type.
type SharedUserData = { [K in SharedUserKeys]: UserProfile[K] } const user1: SharedUserData = { email: 'test@example.com', image: null, username: 'sampleuser', }
相关文章
- TypeScript(node)连接使用MySQL(JavaScript也一样)
- typescript 接口_typeScript
- Typescript: Getting Started
- 【说站】微软官方发布TypeScript 4.4版本
- 「使用 webpack5从0到1搭建React+TypeScript 项目环境」1. React 与 TypeScript 集成
- typeScript学习总结(二)
- 在 Typescript 中使用 Array.filter(Boolean)
- 解决 Typescript 文件被识别为视频的问题
- 【编码规范】Typescript 编码风格指南
- TypeScript 的装饰器有哪些?
- TypeScript 中 as const 是什么
- TypeScript不学?你养我啊[2]
- (一)为什么要使用 TypeScript(二)安装并配置 Ts
- Webpack搭建简单的TypeScript脚手架
- 如何发布一个 TypeScript 编写的 npm 包
- 命令探索Linux系统:使用Find命令(linux中的find)
- 管理利用Linux Find助力企业数据管理(linux find 与)