首页 > 解决方案 > 如何使用作为`* 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;
.....

标签: reactjstypescript

解决方案


我假设您想要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
}

推荐阅读