[Typescript] Get full type safe for discriminatedUnion type with 'type' & 'subtype' (2 levels)
// print
type PrintStart = {
type: "print";
subtype: "start";
attributes: {
controlsId: string;
tabId: number;
};
}
type PrintAbort = {
type: "print";
subtype: "abort";
attributes: {
controlsId: string;
};
}
type PrintLoading = {
type: "print";
subtype: "loading";
attributes: {
controlsId: string;
};
}
type Print = PrintLoading | PrintAbort | PrintStart
// chat
type ChatConnected = {
timestamp?: number | undefined;
type: "chat";
subtype: "connected";
attributes: {
controlsId: string;
component: string;
};
}
type ChatLoading = {
timestamp?: number | undefined;
type: "chat";
subtype: "loading";
attributes: {
controlsId: string;
component: string;
};
}
type ChatUpload = {
timestamp?: number | undefined;
type: "chat";
subtype: "unload";
attributes: {
controlsId: string;
component: string;
};
}
type Chat = ChatUpload | ChatLoading | ChatConnected
// Union of message
type Message = Print | Chat
What we want is that
function sendEncodeMessage(type, subtype, msg) {}
When we give `type` and `subtype`, the `msg` should be narrow down to the exact type
const printStart: PrintStart = {
type: 'print',
subtype: 'start',
attributes: {
tabId: 123,
controlsId: '123',
},
}
function sendEncodeMessage<
Type extends Message['type'],
Sub extends GetMessageSubtypes<Type>,
Msg extends GetMessage<Type, Sub>,
>(type: Type, subtype: Sub, msg: Msg) {}
sendEncodeMessage('print', 'start', printStart) // works
Helpers
export type GetMessagesByType<Type extends Message['type']> = Message extends infer Msg
? Msg extends { type: Type }
? Message
: never
: never
export type GetMessageSubtypes<Type extends Message['type']> = Type extends Message['type']
? GetMessagesByType<Type>['subtype']
: never
export type GetMessage<
Type extends Message['type'],
Subtype extends GetMessageSubtypes<Type>,
> = Message extends infer Msg ? (Msg extends { type: Type; subtype: Subtype } ? Message : never) : never
export type GetMessageAttr<Type extends Message['type'], Subtype extends GetMessageSubtypes<Type>> = GetMessage<
Type,
Subtype
> extends {
attributes: infer Attr
}
? Attr
: never
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2021-01-04 [Java] Modules
2019-01-04 [Tips + Javascript] Make a unique array
2019-01-04 [Algorithm] Median Maintenance algorithm implementation using TypeScript / JavaScript
2019-01-04 [Tools] Support VS Code Navigation and Autocomplete Based on Webpack Aliases with jsconfig.json
2019-01-04 [Tools] Create a Simple CLI Tool in Node.js with CAC
2016-01-04 [Javascript] JSON.parse API
2016-01-04 [React Testing] Setting up dependencies && Running tests