[TypeScript] Combine Template Literal Types usage, Extract and default Generic type

For example we have a type like this:

type Obj = {
  a: "a";
  a2: "a2";
  a3: "a3";
  b: "b";
  b1: "b1";
  b2: "b2";
};

 

We want to constrct a new type which porps starts with letter 'a':

type keyStartingWithA = {
  [K in Extract<keyof Obj, `a${string}`>]: Obj[K];
};

 

So why this works?

Extract: get shared key from 'keyof Obj' (which is "a" | "a1" | "a2" | "b" | "b1" | "b2")

`a${string}` work as wired card: 'a*', * should be type string

So if we change to:

type keyStartingWithA = {
  [K in Extract<keyof Obj, `a${number}`>]: Obj[K];
};

 

OK, now we get Obj back starting with A, if we only want values of it.

type ValuesOfKeysStartingWithA = {
  [K in Extract<keyof Obj, `a${string}`>]: Obj[K];
}[Extract<keyof Obj, `a${string}`>];

 

Then we can improve the type to make it more generic

type ValuesOfKeysStartingWithA<T> = {
  [K in Extract<keyof T, `a${string}`>]: T[K];
}[Extract<keyof T, `a${string}`>];

type NewUnion = ValuesOfKeysStartingWithA<Obj>

 

Finially, you can notice that 

Extract<keyof T, `a${string}`

repeated two times, we can improve those by using default type of Generic types

type ValuesOfKeysStartingWithA<
  T,
  _ExtractedKeys extends keyof T = Extract<keyof T, `a${string}`>
> = {
  [K in _ExtractedKeys]: T[K];
}[_ExtractedKeys];

 

Creates a default variable _ExtractedKeys

Assign it to 

Extract<keyof T, `a${string}`>

Need to use following to keep it working

extends keyof T
posted @   Zhentiw  阅读(59)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2021-04-22 [AWS DA GURU] KMS and Encryption on AWS
2021-04-22 [Linux] Add new sudo user & assign folder owner
2020-04-22 [React] Improve developer experience for accessing context with a custom React hook
2019-04-22 [Functional Programming] From simple implementation to Currying to Partial Application
2016-04-22 [CSS3] CSS Media Queries
点击右上角即可分享
微信分享提示