繁体   English   中英

如何使用在 adts 文件中定义的类型的模块?

[英]How to use a module with types defined in a .d.ts file?

我开始使用react-native-web ,并尝试使用 typescript 这样做。 到目前为止没有太大的成功。 根据这个问题,如果我创建一个.d.ts文件,typescript 将从那里获取类型,但值将从非.d.ts文件中获取。

对我来说,它抛出'Icon' only refers to a type, but is being used as a value here. .

我在一个名为Spinner.tsx的文件中使用它,像这样导入它: import { Icon } from '../Icon'; ,我的文件结构如下:

Icon
  index.native.tsx
  index.web.tsx
  index.d.ts

index.native.tsx

import React, { FC } from 'react';
import { ViewStyle } from 'react-native';
import RNVIcon from 'react-native-vector-icons/Ionicons';
import { IconProps } from './index.web';

export const Icon: FC<Omit<IconProps, 'style'> & { style: ViewStyle }> = ({ name, ...props }) => {
  const RNVIName = name
    .replace(/io/i, '')
    .replace(/[A-Z][a-z]*/g, (str) => '-' + str.toLowerCase() + '-')
    .replace(/--/g, '-')
    .replace(/(^-)|(-$)/g, '');

  return <RNVIcon name={RNVIName} {...props} />
};

index.web.tsx

import React, { CSSProperties, FC } from 'react';
import * as Icons from 'react-icons/io5';
import { ViewStyle } from 'react-native';

export type IconProps = {
  name: keyof typeof Icons;
  size?: number;
  color?: string;
  style?: ViewStyle;
}

export const Icon: FC<Omit<IconProps, 'style'> & { style: CSSProperties }> = ({ name, ...props }) => {
  const Component = Icons[name];

  return <Component {...props} />
}

index.d.ts

import { FC } from "react";
import { IconProps } from "./index.web";

export type Icon = FC<IconProps>

我也尝试过默认导出,但没有成功。 我究竟做错了什么?

您的问题部分是您的输入正在解析为 index.d.ts 文件。 (参见: https://www.typescriptlang.org/docs/handbook/module-resolution.html#how-typescript-resolves-modules

也就是说,即使您有一个从每个单独文件中导出 Icon 的 index.ts 文件,您也会遇到命名冲突。 如果要导出具有相同名称的类型和值,我知道的唯一解决方法是从同一个文件中导出它们。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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