TypeScript中能否实现返回类型名称的泛型函数get_ts_type?
问题:能否实现返回泛型类型名称的
get_ts_type函数? 测试代码
interface TheType{ name:string } function get_ts_type<T>(): string { return // todo: implement this } function test_it(){ const ans=get_ts_type<TheType>() console.log(ans) //should print TheType } test_it()
问题:是否可以实现上述get_ts_type函数,使其在测试程序中返回"TheType"?
实际使用场景代码
export function cast<T extends Node>(node:Node):T|null{ const typestring=get_ts_type<T>() if (node.type == typestring) return node as T return null } function process_node(elem:Node){ const fdecl=cast<FunctionDeclaration>(elem) if (fdecl){ const field_name=fdecl.id.name console.log(field_name) } }
补充说明:这并非重复问题,核心聚焦于类型守卫与泛型,而非运行时检查。
回答
不行,无法直接实现get_ts_type函数。因为TypeScript的泛型是编译时特性,编译后所有泛型信息都会被擦除,运行时根本无法获取到泛型参数对应的类型名称。
针对你的Acorn类型守卫场景,推荐以下几种替代方案:
1. 手动传入类型名称参数
修改cast函数,让调用者显式传递类型字符串,确保运行时能拿到匹配的值:
export function cast<T extends Node>(node: Node, typeName: string): T | null { if (node.type === typeName) { return node as T; } return null; } function process_node(elem: Node) { const fdecl = cast<FunctionDeclaration>(elem, "FunctionDeclaration"); if (fdecl) { console.log(fdecl.id.name); } }
2. 用常量映射避免字符串硬编码
提前定义Acorn节点类型的常量映射,减少手动输入错误:
const NodeTypes = { FunctionDeclaration: "FunctionDeclaration", // 补充其他需要的节点类型 } as const; export function cast<T extends Node>(node: Node, typeKey: keyof typeof NodeTypes): T | null { if (node.type === NodeTypes[typeKey]) { return node as T; } return null; } function process_node(elem: Node) { const fdecl = cast<FunctionDeclaration>(elem, "FunctionDeclaration"); if (fdecl) { console.log(fdecl.id.name); } }
3. 自定义类型守卫函数(最推荐)
针对每个具体节点类型编写专属的类型守卫,这是最符合TypeScript类型系统规范的方式,类型安全性最高:
function isFunctionDeclaration(node: Node): node is FunctionDeclaration { return node.type === "FunctionDeclaration"; } function process_node(elem: Node) { if (isFunctionDeclaration(elem)) { console.log(elem.id.name); } }
总结:TypeScript不会保留运行时的类型元数据,所以无法通过泛型参数直接获取类型名称。上述方案都能实现你需要的类型守卫功能,其中自定义类型守卫的写法最直观、安全。
内容的提问来源于stack exchange,提问作者yigal
相关产品推荐
相关产品推荐

