TypeScript赋值报错:string|boolean|null无法赋值给null/never类型
TypeScript共享值类型赋值错误解决方法
问题代码
type ContextProps = Record< "template" | "folder" | "repository" | "projectPath" | "baseName", string | null >; type InstallDependenciesProps = Record<"installDependencies", boolean | null>; type CombinedProps = ContextProps & InstallDependenciesProps; const context: CombinedProps = { template: null, folder: null, repository: null, projectPath: null, baseName: null, installDependencies: false, }; const setValue = ( key: keyof CombinedProps, value: CombinedProps[keyof CombinedProps] ) => { context[key] = value; // 此处抛出类型错误 };
错误信息
Type 'string | boolean | null' is not assignable to type 'null'. Type 'string' is not assignable to type 'null'.
问题原因
当前setValue函数的类型定义中,value是CombinedProps所有属性值类型的联合(string | boolean | null),但TypeScript无法确保传入的value类型和key对应的属性类型一致。比如当key为installDependencies时,属性值类型应为boolean | null,但函数允许传入string | null,导致类型不兼容。使用Partial或Optional仅修改属性可选性,无法解决key与value的类型关联问题,因此仍会报错。
解决方案
将setValue改为泛型函数,通过泛型约束让key和对应的value类型严格匹配:
const setValue = <K extends keyof CombinedProps>( key: K, value: CombinedProps[K] ) => { context[key] = value; };
这样TypeScript会根据传入的key自动推断出对应的value类型,确保类型完全兼容,不会再出现赋值错误。
内容的提问来源于stack exchange,提问作者chadjohnson
相关产品推荐
相关产品推荐

