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

TypeScript使用Record工具类型遇类型约束错误的解决方法

TypeScript 可选属性联合类型作为Record键的修复方案

问题根源

你定义的ThreeStringProps中vars是可选属性,所以ThreeStringProps['vars']的实际类型是'prop1' | 'prop3' | undefined。而Record<K, T>要求键类型K必须是string | number | symbol,不能包含undefined,这就是报错的原因。Required工具类型仅用于将接口的可选属性转为必填,无法去除类型中的undefined,所以无效。

修复方案

方案1:用Exclude排除undefined

通过Exclude工具类型从联合类型中移除undefined,得到合法的键类型:

interface ThreeStringProps {
  vars?: 'prop1' | 'prop3';
}

type ObjType = Record<Exclude<ThreeStringProps['vars'], undefined>, string>;
const obj: ObjType = {
  prop1: 'value1',
  prop3: 'value3'
};

方案2:直接使用原始联合类型

如果vars的可选值是固定的,直接用原始联合类型定义Record的键,跳过从接口属性提取的步骤:

interface ThreeStringProps {
  vars?: 'prop1' | 'prop3';
}

type ObjType = Record<'prop1' | 'prop3', string>;
const obj: ObjType = {
  prop1: 'value1',
  prop3: 'value3'
};

方案3:抽离单独的类型别名(推荐)

把vars的可选值抽成独立的类型别名,既保证类型一致性,又避免重复定义:

// 抽离vars的可选值类型
type VarsType = 'prop1' | 'prop3';

interface ThreeStringProps {
  vars?: VarsType;
}

type ObjType = Record<VarsType, string>;
const obj: ObjType = {
  prop1: 'value1',
  prop3: 'value3'
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 09:55:28