Handle self written types definition in TypeScript project

泄露秘密 提交于 2021-02-08 08:45:25

问题


In my React project using TypeScript I wrote some types definition that I need to reuse in many other files like for example the type:

type TIconName = 'menu' | 'shop' | 'user' 

To make this type available in all my project I use a types.ts file that lies at the root and that export all my types:

/types.ts

export type TIconName = 'menu' | 'shop' | 'user' 
...

So now I'm able to import all the types like this one in all my files with only one import:

/component/icon/Icon.tsx

import { TIconName, TOtherType, ... } from '../../types'
...

With the use of an alias @types that refer to types.ts it makes importing even easier:

/component/deeperComponent/component.tsx

import { TIconName, TOtherType, ... } from '@types'
...




My type TIconName belong to the React component /component/icon/Icon.tsx wich is basically typed with an interface for his props:

/component/icon/Icon.tsx

import React from 'react'
import { TIconName } from 'types'

interface Props {
  iconName: TIconName
}

// C O M P O N E N T
const Icon: React.FunctionComponent<Props> = (props) => {
  ...

My problem is I'd like to get access to this type without having to import him like React do with his type React.FunctionComponent<...>.

I know in order to do that I'd have to write a .d.ts file. So I wrote one called index.d.ts in the same folder that my Icon component:

/component/icon/index.d.ts

type TIconName = 'menu' | 'shop' | 'user' 

But if I import my Icon component in an other file, typescript doesn't recognise/import the type TIconName:

/component/user/User.tsx

import Icon from '../icon/Icon'

const test: TIconName   // <- Cannot find name 'TIconName'

Do you have any idea what I forgot or where the problem is?

来源:https://stackoverflow.com/questions/60740173/handle-self-written-types-definition-in-typescript-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!