NextJS:如何解决‘Type 'string' is not assignable to type...’类型错误
解决方法
以下是几种可行的修复方案:
方案1:使用类型断言指定字面量类型
在传入组件属性时,通过as将字符串断言为对应的字面量类型,让TypeScript识别其具体类型而非宽泛的string:
<Button text="Click me" theme="primary" as 'primary' size="large" as 'large' onClick={clickHandler} />
方案2:优化组件的类型定义
先通过const断言定义固定的可选值集合,再基于此生成对应的类型,确保TypeScript能准确推断属性的字面量类型:
// 定义固定的可选值集合 const ButtonThemes = ['primary', 'secondary'] as const; const ButtonSizes = ['small', 'medium', 'large'] as const; // 基于集合生成字面量类型 export type ButtonTheme = typeof ButtonThemes[number]; export type ButtonSize = typeof ButtonSizes[number]; // 组件接口 interface IButton { text: string; theme: ButtonTheme; size: ButtonSize; onClick: () => void; } // Button组件实现 const Button = ({ text, theme, size, onClick }: IButton) => { return <button className={`btn-${theme} btn-${size}`} onClick={onClick}>{text}</button>; };
方案3:用const断言包裹属性值
在传递属性时,用as const直接把字符串值转为字面量类型:
<Button text="Click me" theme={"primary" as const} size={"large" as const} onClick={clickHandler} />
方案4:启用TypeScript专属配置(TS 5.1+)
如果项目使用TypeScript 5.1及以上版本,可在tsconfig.json中启用jsx-string-literal-types配置,让TypeScript自动将JSX中的字符串字面量推断为对应字面量类型:
{ "compilerOptions": { "jsx": "preserve", "jsx-string-literal-types": true } }
内容的提问来源于stack exchange,提问作者ST80
相关产品推荐
相关产品推荐

