简体   繁体   中英

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

I started using react-native-web , and trying to do so with typescript. So far not much success. According this question , if I create a .d.ts file, typescript will get the types from there, but the values will be get from the not .d.ts files.

For me it throws 'Icon' only refers to a type, but is being used as a value here. .

I'm using it in a file called Spinner.tsx , importing it like: import { Icon } from '../Icon'; , my file structure looks like:

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>

I have tried with default export as well, no success. What am I doing wrong?

Your problem is partially that your input is resolving to the index.d.ts file. (see: https://www.typescriptlang.org/docs/handbook/module-resolution.html#how-typescript-resolves-modules )

That said, even if you had an index.ts file that exported Icon from each individual file, you would have a naming collision. The only workaround I'm aware of if you want to export a type and a value with the same name is to export them from the same file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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