React TypeScript:如何绕过类型检查强制传递Props
绕过第三方库组件类型检查传递未声明Props的方法
当第三方库组件的类型定义缺失你需要传递的Props(比如className)时,除了声明合并,你可以用以下几种方式直接绕过类型检查:
用
as any断言组件类型
将组件直接断言为any,TypeScript会允许传递任意Props:<(LibraryComponent as any) className="foo" />使用
@ts-ignore忽略单行错误
给报错行添加注释,临时屏蔽类型检查(注意:该注释会忽略整行所有类型问题,不建议长期依赖):// @ts-ignore <LibraryComponent className="foo" />展开断言为
any的额外Props对象
把未声明的Props放到单独对象中,断言为any后展开传递:const extraProps = { className: "foo" } as any; <LibraryComponent {...extraProps} />扩展组件类型并断言
自定义包含缺失Props的类型,再将组件断言为该类型,相对更精准:type ExtendedLibraryProps = typeof LibraryComponent & { props: { className?: string }; }; <(LibraryComponent as ExtendedLibraryProps) className="foo" />
以上都是临时规避类型错误的方案,长期来看,通过自定义类型文件进行声明合并补全缺失的类型定义,是更规范的做法。
内容的提问来源于stack exchange,提问作者Nathan
相关产品推荐
相关产品推荐

