reactjs - 如何使用作为`* as`导入的Typescript定义
问题描述
我正在使用react-icons
并尝试将所有图标定义导入为import * as Icons from 'react-icons/fi'
问题是如何创建一个应该是从 Icons 导出的类型之一的类型
例如,我正在尝试制作这样的道具界面:
interface Props {
icon: Icons // don't know what to do here
}
这是react-icons/fi/index.d.ts
文件的样子:
export declare const FiActivity: IconType;
export declare const FiAirplay: IconType;
export declare const FiAlertCircle: IconType;
export declare const FiAlertOctagon: IconType;
export declare const FiAlertTriangle: IconType;
export declare const FiAlignCenter: IconType;
.....
解决方案
我假设您想要Icons
命名空间中所有 Icon 常量的名称,因为所有 Icons 的类型似乎都是相同的IconType
。
在这种情况下,您可以使用keyof
和的组合typeof
来实现:
import * as Icons from 'react-icons/fi'
interface Props {
icon: keyof typeof Icons
}
typeof
将为您提供图标的类型。keyof
然后将该类型的键的名称作为联合类型返回。所以你得到的类型最终会是'FiActivity' | 'FiAirplay' | 'FiAlertCircle' | ...
.
如果您想接受任何这些 const 作为一个整体作为道具,而不仅仅是名称,那么您可以直接使用IconType
。
import * as Icons from 'react-icons/fi';
import {IconType} from 'react-icons';
interface Props {
icon: IconType
}
推荐阅读
- multithreading - 是否可以在 Opencv Gstreamer 之间运行并行连接?
- python-3.x - 如何分离 HID 的系统 USB 驱动程序?
- python - 如何在#Python 中通过按回车键自动添加数字
- javascript - 日期选择器 - 具有辅助功能 - 兼容 IE11 及更高版本
- ios - 异步返回用户的经纬度
- python-3.x - 如何将 importlib.resources 与 pickle 文件一起使用?
- amazon-web-services - 假设我是 AWS IAM 用户,有什么方法可以让我使用 CLI 或控制台检查已授予我哪些资源权限
- python-3.x - 为什么 hyperopt 在随机森林中运行时会给出最好的损失 Nan?
- ruby-on-rails - AWS:Ruby describe_instance_type_offerings() 给出异常:“未定义的方法”
- vue.js - Vue Router Meta 对象未定义