[Typescript] Tips: Turn a module into a type

Want to turn a module into a type? You can use typeof import('./') to grab the type of any module, even third-party ones.

Here, we create a type from a constants.ts file, then map over the values to create a union.

For example we have a constants.ts:

export const ADD_TODO = "ADD_TODO";
export const EDIT_TODO = "EDIT_TODO";
export const REMOVE_TODO = "REMOVE_TODO";

 

Instead of doing as such: types.ts

export type Action = 'ADD_TODO' | 'EDIT_TODO' | 'REMOVE_TODO';

 

We want to dynamic approach:

export type ActionModule = typeof import('./constants');
export type Action = ActionModule[keyof ActionModule];

 


 

This example deps on how you name your "Re-export":

types/chat.ts:

export const SUBTYPE = {
  UP: "up",
  CONNECTED: "connected",
  LOADING: "loading",
  UNLOAD: "unload",
} as const;
export const TYPE = "chat";

types/devtools.ts:

export const TYPE = "devtools";
export const SUBTYPE = {
  OPEN: "open",
} as const;

types/index.ts

export * as chat from "./chat"; // naming is important, as chat should the same as const TYPE = "chat"
export * as devtools from "./devtools";

index.ts:

import { chat, devtools } from "./types/index";

export type ActionModule = typeof import("./types/index");
export type Action = ActionModule[keyof ActionModule];

function sendMessage<K extends Action["TYPE"], U extends ActionModule[K]["SUBTYPE"]>(
  dataType: K,
  subtype: U[keyof U]
) {}

sendMessage(chat.TYPE, chat.SUBTYPE.CONNECTED); // works
sendMessage(chat.TYPE, devtools.SUBTYPE.OPEN);  // nope Argument of type '"open"' is not assignable to parameter of type '"up" | "connected" | "loading" | "unload"'.

 

posted @   Zhentiw  阅读(16)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2020-10-15 [Kotlin] Using Kotlin from Java
2020-10-15 [Kotlin] Using Java from Kotlin
2020-10-15 [Kotlin] Companion object with @JvmStatic
2020-10-15 [Kotlin] Method expressions
2020-10-15 [Kotlin] companion object == static method
2020-10-15 [Kotlin] Shorthand syntax for FP
2019-10-15 [Svelte 3] Render HTML directly into a component in Svelte 3
点击右上角即可分享
微信分享提示