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

能否用keyof定义模板字面量类型?TypeScript类型报错求助

解决TypeScript模板字面量中Symbol类型不兼容问题

问题根源

keyof FormSchema 默认会包含 string | number | symbol 三种类型,而模板字面量仅支持字符串类型,因此当尝试将symbol类型代入模板时会触发Type 'symbol' is not assignable to type 'string'错误。即使给默认泛型参数设置了string索引签名,TypeScript仍会将keyof解析为string | number | symbol(这是因为对象键允许隐式转换为这三种类型)。

解决方案

方案1:过滤出字符串类型的键

使用Extract<keyof FormSchema, string>提取FormSchema中仅字符串类型的键,避免symbol混入模板字面量:

export type FormSection<
  FormSchema extends Record<string, any | Record<string, any>> = Record<string, any | Record<string, any>>
> = {
  id: string;
  elements: FormElementGeneric<
    Extract<keyof FormSchema, string> | `${Extract<keyof FormSchema, string>}.${string}`,
    FormInputTypes,
    FormInputTypesProps
  >[];
};

方案2:明确约束键为字符串类型

直接将FormSchema的键约束为string,这样keyof FormSchema只会返回string类型,无需额外过滤:

export type FormSection<
  FormSchema extends { [K in string]: any | { [K in string]: any } } = { [K in string]: any | { [K in string]: any } }
> = {
  id: string;
  elements: FormElementGeneric<
    keyof FormSchema | `${keyof FormSchema}.${string}`,
    FormInputTypes,
    FormInputTypesProps
  >[];
};

测试验证

用你提供的示例FormSchema测试:

type FormSchema = { username: string; settings: { theme: string; language: string } }
type TestSection = FormSection<FormSchema>
// elements的id类型为:"username" | "settings" | "username.${string}" | "settings.${string}",完全符合预期

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 21:15:13