2

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 which 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 recognize/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?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
johannchopin
  • 13,720
  • 10
  • 55
  • 101
  • https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html – Roberto Zvjerković Mar 18 '20 at 13:13
  • @ritaj Thanks for the link but can you please be more specific of what my error is ? Because I wrote my type definition in a `global` but it's still not work: `declare global { type TIconName = 'menu' | 'shop' | 'user' }`. And just read the structure of this `.d.ts` file don't help me more :( – johannchopin Mar 18 '20 at 14:08

0 Answers0