簡體   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