TypeScript中为何string类型无法赋值给字符串联合类型?
TypeScript:string类型无法赋值给字符串联合类型的问题
定义的类型
我定义了以下字符串联合类型:
type FormFieldName = | "product details" | "objectives" | "stakeholders" | "functional requirements" | "non-functional requirements" | "assumptions and constraints" | "dependencies" | "acceptance criteria" | "risk analysis" | "priority effort" | "version history";
同时定义了PrdDataObject相关类型:
type PrdFormFieldsParamDefault = string | number | boolean | unknown[] | null; type PrdFormFields<T> = { name: string; details: { [key: string]: T | PrdFormFields<T> | PrdFormFields<T>[] }; }; type PrdDataObject< T = | PrdFormFieldsParamDefault | Record<string, PrdFormFieldsParamDefault> | Record<string, PrdFormFieldsParamDefault>[], > = { type: string | null; title: string | null; chosenLanguage: string | null; formFields: PrdFormFields<T>[] | null; };
问题场景
我尝试为reduce方法中的累加器对象fieldsObject设置类型,代码如下:
const internalFormFields = prdDetails.formFields.reduce( (fieldsObject, field) => { const name: FormFieldName = field.name as FormFieldName; fieldsObject[name] = field.name; return fieldsObject; }, {} as { [key in FormFieldName]: FormFieldName; } );
执行到fieldsObject[name] = field.name;时,TypeScript报错:
Type 'string' is not assignable to type 'FormFieldName'
已尝试的方案
- 试过多种类型断言方式,均无效
- 认为类型守卫不是合适的解决方案
- 查阅过Stack Overflow相关问题,未找到适配的解决办法
内容的提问来源于stack exchange,提问作者Henry Ozoani
相关产品推荐
相关产品推荐

