Home > database >  React/TypeScript: Exporting/Importing Types and Interfaces vs Types and Interfaces in Declaration fi
React/TypeScript: Exporting/Importing Types and Interfaces vs Types and Interfaces in Declaration fi

Time:03-03

In a React TypeScript project, there are 2 ways we can use Types and Interfaces.

  1. Create and export a type/interface in a file (e.g. FileA) and import it and use it in another file (FileB). for e.g.
// FileA.ts

export interface Foo {
   foo: number;
}

//FileB.ts
import {Foo} from ./FileA;

  1. The other approach is we can create a declaration file for e.g. types.d.ts and any interface/type defined in this file is automatically in the whole app and we don't have to import/export those.

The question is which approach is better and should be used? I mean does import/export have a cost attached to it like in the first one?

Thanks

CodePudding user response:

Import/export of types in typescript should have no cost, since it is compiled into js and has nothing to do with performance, bundle size, etc..

While declaring interfaces for the whole project can sound good, it can lead to mess and problems like redeclaring global types with local ones. Especially as your project grows.

I suppose you should try to always use .ts files and import them where you need them.

Use declaration types .d.ts if you need to declare types for .js files, specify types for a module/library, declare types for variables from other scripts, or for files that typescript does not recognize (.env, etc...).

Take a look at official typescript documentation to find out more about .d.ts file usage.

  • Related