1

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

1
  • 1
    I prefer the second approach. You can also declare the namespace in the first one so it will usually be not from './FileA' rather it will be from 'projectName'. I think it just makes a central place for all the types you need. Also I think there wouldn't be an import price since types aren't used in production and runtime. -- Yeah tsc doesn't import types lmao Commented Mar 1, 2022 at 23:01

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.