[Typescript] Default value for Builder pattern - 04 (keyof {} -> never)

From previous post, Builder pattern - 03

If we do the following changes:

- class TypeSafeStringMap<TMap extends Record<string, string> = {}> {
+ class TypeSafeStringMap<TMap extends Record<string, string>> {

It has a big impact of the codebase:

When we have the default value:

class TypeSafeStringMap<TMap extends Record<string, string> = {}> {}

const map = new TypeSafeStringMap()
//      ^? TypeSafeStringMap<{}>

When we don't have the default value:

class TypeSafeStringMap<TMap extends Record<string, string>> {}

const map = new TypeSafeStringMap()
//      ^? TypeSafeStringMap<Record<string, string>>

So, when we set/get the value, we will see the differences

class TypeSafeStringMap<TMap extends Record<string, string> = {}> {}

const map = new TypeSafeStringMap().set('name', 'abc')
//  map: TypeSafeStringMap<Record<"name", string>>
class TypeSafeStringMap<TMap extends Record<string, string>> {}

const map = new TypeSafeStringMap().set("name", "abc")
//      ^? TypeSafeStringMap<Record<string, string> & Record<"name", string>>

Take a close look of difference:

// with default {} 
TypeSafeStringMap<Record<"name", string>>

// without default {}
TypeSafeStringMap<Record<string, string> & Record<"name", string>>

When we have getter function:

  get(key: keyof TMap): string {
    return this.map[key];
  }

// without default value
type a = keyof Record<"name", string>
//    ^? "name"
type b = keyof (Record<string, string> & Record<"name", string>)
//    ^? string

b is type string, because string | "name" results in string type.

Why a work fine, this is because

type c = keyof {}
//    ^? never
type d = never | "name"
//    ^? "name"

Tips:

type isNever<T> = [T] extends [keyof {}] ? true: false;

type e = isNever<never> // true
type f = isNever<false> // false
posted @   Zhentiw  阅读(18)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2020-02-14 [Angular 8 Unit Testing] Testing a dump component
2020-02-14 [Functional Programming] Use a Javascript Array to Construct a Maybe
2018-02-14 [Angular + Unit Testing] Mock HTTP Requests made with Angular’s HttpClient in Unit Tests
2018-02-14 [Angular] Provide Feedback to Progress Events with Angular’s HttpRequest Object
2018-02-14 [Angular] Fetch non-JSON data by specifying HttpClient responseType in Angular
2018-02-14 [Angular] Read Custom HTTP Headers Sent by the Server in Angular
2018-02-14 [Angular] Set Metadata in HTTP Headers with Angular HttpHeaders
点击右上角即可分享
微信分享提示