简体   繁体   English

使用 Typescript 导入文件

[英]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:但是,您应该修复代码中的许多不良做法:

  1. You should add a import * as icons from "./pathToIcons";您应该添加一个import * as icons from "./pathToIcons"; . . Importing by the index.ts should only happen if importing from outside the same folder;仅当从同一文件夹外部导入时才应通过 index.ts 导入;
  2. const icon = (...) A component should start with capital letter, const Icon = (...) ; const icon = (...)一个组件应该以大写字母开头, const Icon = (...)
  3. { 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM