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

如何创建利用对象信息推断新类型的Type Helper

解决方案

问题根源

你手动给columns标注了Column[]类型,这会让TypeScript将数组元素里的具体字面量(比如"id"、"numeric")自动拓宽为通用类型(string、"numeric"|"text"),导致后续无法提取到具体的字段名和对应的类型映射关系。

步骤1:保留字面量类型

要让TypeScript保留数组元素的具体字面量类型,不能直接标注Column[],可以通过泛型辅助函数约束值符合Column类型的同时,保留原始字面量信息:

type Column = Readonly<{ type: "numeric" | "text"; name: string }>;

// 辅助函数:约束输入符合Column数组类型,同时捕获字面量类型
const createColumns = <T extends readonly Column[]>(columns: T) => columns;

// 创建columns时用辅助函数,结合as const断言锁定字面量
const columns = createColumns([
    { type: "numeric", name: "id" },
    { type: "text", name: "firstName" },
] as const);

步骤2:实现TypeOfColumns工具类型

通过映射类型遍历数组元素的name作为键,再通过Extract提取对应name的元素类型,最后根据type映射为number或string:

type TypeOfColumns<T extends readonly Column[]> = {
    // 遍历数组中每个元素的name作为对象键
    [K in T[number]["name"]]: 
        // 提取当前name对应的元素类型
        Extract<T[number], { name: K }>["type"] extends "numeric" 
            ? number  // type为numeric时映射为number
            : string; // 否则映射为string
};

验证结果

此时使用TypeOfColumns<typeof columns>就能得到预期类型:

type ColumnType = TypeOfColumns<typeof columns>;
// 推断结果:{ id: number; firstName: string }

为什么你的尝试无效?

你之前的代码中,columns被标注为Column[],导致T[number]["name"]被解析为string(而非具体的"id"、"firstName"),同时T[number]是Column的联合类型,最终生成的是带字符串索引的模糊类型,而非预期的具体键值对。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 19:40:26