[Typescript] Be Specific for Better Inference
This exercise begins with a makeStatus
function that takes in an array of TStatuses
that extends an array of strings. The statuses are then returned, kind of like an identity function:
const makeStatus = <TStatuses extends string[]>(statuses: TStatuses) => {
return statuses;
};
Looking at the tests, we can see that we're expecting statuses
to be an array of INFO
or DEBUG
or ERROR
or WARNING
, all of the things that we pass in here.
const statuses = makeStatus(["INFO", "DEBUG", "ERROR", "WARNING"]);
// ^? string[]
type tests = [
Expect<Equal<typeof statuses, Array<"INFO" | "DEBUG" | "ERROR" | "WARNING">>>, // not working
];
However that's not what we're getting-- instead, we just get an array of strings.
So idea is to get actual value of each string array memeber.
In Typescript compiler, if you use generic on array level, then it infer typeof this array
["INFO", "DEBUG", "ERROR", "WARNING"] // string[]
["INFO", "DEBUG", "ERROR", 1] // (string | number)[]
[1,2,3,4] // number[]
[1,2,3,undefined] //(number | undefined)[]
So, if you want to get so array member as type, you have to go deeper, which means, the generic type cannot be array level any more, it needs to be array member level.
const makeStatus = <TStatus extends string>(statuses: TStatus[]) => {
return statuses;
};
So we got correct results.
const statuses = makeStatus(['INFO', 'DEBUG', 'ERROR', 'WARNING']);
// ^? ("INFO" | "DEBUG" | "ERROR" | "WARNING")[]
type tests = [
Expect<Equal<typeof statuses, Array<'INFO' | 'DEBUG' | 'ERROR' | 'WARNING'>>>
];
If we change the array to be (number | string)[]
const makeStatus = <TStatus extends string | number>(statuses: TStatus[]) => {
return statuses;
};
const statuses = makeStatus([1, 'DEBUG', 'ERROR', 'WARNING']);
// ^? (1 | "DEBUG" | "ERROR" | "WARNING")[]
type tests = [
Expect<Equal<typeof statuses, Array<1 | 'DEBUG' | 'ERROR' | 'WARNING'>>>
];
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2020-01-16 [NGXS] Select - 3. @Selector orders matter
2020-01-16 [NGXS] Selector - 2 Joining Selectors, compose
2020-01-16 [NGXS] Select - 1
2020-01-16 [NGXS] Using Immer with NGXS
2020-01-16 [Typescript] Namespaces
2020-01-16 [Algorithm] 14. Longest Common Prefix -- 4
2019-01-16 [Spring Boot] Adding JPA and Spring Data JPA