0

I would like to separate the type and interface definitions from my component code. This would make the jsx file smaller and easier te read.

I created the following two files:

./Header/Header.d.ts

export type HeaderProps = {
  logo?: string;
}

For the following component:

./Header/Header.tsx

import React from 'react';
import { HeaderProps } from './Header'; // gives error

const Header: React.FC<HeaderProps> = ({ logo }) => (
  <header>
    <img src={logo} alt="Logo" />
  </header>
);

However I can't import the type declaration file in my component. I receive the following error:

TS2614: Module '../Header/Header' has no exported member 'HeaderProps'. Did you mean to use 'import HeaderProps from '../Header/Header'?

Am I doing this wrong?

Remi
  • 4,663
  • 11
  • 49
  • 84
  • When I rename the file to `./Header/Header.interface.ts` and then import it using that filename it works. I guess the `*.d.ts` is a different type of file and should not be used for this purpose? – Remi Nov 24 '19 at 10:10

1 Answers1

1

you don't need to import the HeaderProps AFAIK when you declare it on .d.ts

khierl
  • 605
  • 1
  • 6
  • 16
  • Thanks for the response. You could be right, my editor shows that the Header.d.ts file is a sub-file of the Header.tsx. But when I remove the import, how would the component then know the type definitions? I get the error TS2304: Cannot find name 'HeaderProps'. – Remi Nov 24 '19 at 17:19
  • https://stackoverflow.com/a/21247316/8879305 the better way is to declare the typings within your Header component and export it and be accessible anywhere. – khierl Nov 25 '19 at 11:38
  • Aha. So the `.d.ts` file is something that get's generated by Typescript itself. So it's function is only to communicate the API of the component you're working on to other components, not so much to re-use it in the component itself. – Remi Nov 25 '19 at 14:17