能否用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
相关产品推荐
相关产品推荐

