[英]File importing with Typescript
I'm importing the file, but I can't give the type of the file, how can I solve this problem?我正在导入文件,但是我不能给出文件的类型,我该如何解决这个问题?
import { capitalize } from "utils";
import * as Icons from "./";
type IconType = {
name: string;
};
const icon = ({ name, ...props }: IconType) => {
const newName = capitalize(name);
if (!Icons[newName]) return null;
const CustomIcon = Icons[newName];
return <CustomIcon {...props} />;
};
export default icon;
You can probably fix your issue by typing Icons[newName as keyof Icons]
.您可以通过键入
Icons[newName as keyof Icons]
来解决您的问题。
You have a lot of bad practices in your code you should fix, though:但是,您应该修复代码中的许多不良做法:
import * as icons from "./pathToIcons";
import * as icons from "./pathToIcons";
. const icon = (...)
A component should start with capital letter, const Icon = (...)
; const icon = (...)
一个组件应该以大写字母开头, const Icon = (...)
;{ name, ...props }: IconType
This is incoherent, because your type IconType
only has one attribute name
, therefore in your case, typescript should infer props typeof never
. { name, ...props }: IconType
这是不连贯的,因为您的类型IconType
只有一个属性name
,因此在您的情况下,typescript 应该推断props typeof never
。 Probably you want something interface IconProps extends CustomIconProps { name: string }
interface IconProps extends CustomIconProps { name: string }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.