You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Typescript中实现类型与字符串双向映射的解决方案咨询

核心前提

TypeScript 采用类型擦除的编译策略,所有仅存在于类型空间的定义(type/interface/泛型参数)编译后都会被完全删除,因此不可能仅通过Query<BlogPost>()这种仅传递泛型参数的写法,在运行时获取到BlogPost对应的字符串值。要实现双向映射,必须先定义同时存在于「类型空间+运行时空间」的映射载体,所有类型从该载体推导,避免重复编码。


方案1:使用 Class 作为映射载体(推荐,维护成本最低)

利用 Class 同时存在于类型空间和运行时空间的特性,每个文档类型自己维护对应的字符串标识,无需额外映射表。

实现步骤

  1. 定义基础文档类和具体业务类
abstract class BaseDocument {
  abstract readonly type: string;
}

class BlogPost extends BaseDocument {
  readonly type = 'blog-post' as const;
  title: string;
  // 其他业务字段
}

class Page extends BaseDocument {
  readonly type = 'page' as const;
  content: string;
  // 其他业务字段
}
  1. 封装查询方法
function Query<T extends BaseDocument>(docClass: new () => T) {
  // 直接从类原型取运行时的字符串标识
  const docType = docClass.prototype.type;

  return {
    async all(): Promise<T[]> {
      // 拼接API查询条件即可,比如 document.type == docType
      const res = await fetch(`/api/documents?type=${docType}`);
      return res.json() as Promise<T[]>;
    }
  }
}

调用方式

和期望的写法几乎一致,仅多传一个类名作为运行时标记,类型自动关联,无硬编码:

// 返回 Promise<BlogPost[]>
Query(BlogPost).all()
// 返回 Promise<Page[]>
Query(Page).all()

方案2:使用运行时映射表推导类型(适合不想用 Class 的场景)

仅维护一份运行时映射表,所有类型自动从该表推导,不需要重复定义interface/type。

实现步骤

  1. 定义唯一需要手动维护的运行时映射表
// 键为字符串ID,值为对应类型的结构定义
const DOC_TYPE_MAP = {
  'blog-post': { type: 'blog-post', title: '' },
  'page': { type: 'page', content: '' }
} as const;
  1. 从映射表自动推导所有需要的类型
// 字符串ID联合类型:'blog-post' | 'page'
type DocTypeKey = keyof typeof DOC_TYPE_MAP;
// 文档类型联合:BlogPost | Page
type DocumentType<K extends DocTypeKey = DocTypeKey> = typeof DOC_TYPE_MAP[K];

// 支持你之前需要的字符串反查类型
type BlogPost = DocumentType<'blog-post'>;
type Page = DocumentType<'page'>;
  1. 封装查询方法
function Query<K extends DocTypeKey>(docType: K) {
  return {
    async all(): Promise<DocumentType<K>[]> {
      const res = await fetch(`/api/documents?type=${docType}`);
      return res.json() as Promise<DocumentType<K>[]>;
    }
  }
}

调用方式

传入字符串时有完整的类型提示,返回值自动关联对应类型:

// 返回 Promise<BlogPost[]>
Query('blog-post').all()
// 返回 Promise<Page[]>
Query('page').all()

内容的提问来源于stack exchange,提问作者Thor Correia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 16:54:03