[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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源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