ZChu
ZChu

Reputation: 45

Custom types across multiple .ts/.tsx files

I'm trying to build up my first project with Typescript (and React/Redux) and struggling to pass my custom types between multiple files: like making my action types available to action creators, reducer, and each component dispatching some of those actions.

So, what's the proper approach here:

I understand that this question may be closed as rather opinionated, but I failed to find the answer neither in typescriptlang.org nor in the other resources (including SO topics).

Upvotes: 3

Views: 580

Answers (2)

hossein sedighian
hossein sedighian

Reputation: 2055

place all of your types into a module and call filename.d.ts

//filename.d.ts

  declare module "my-module"{
    
      export type int = number;
    
    
    {

if you want to use enum place it on .ts file (not d.ts)

Upvotes: 1

Wolfie
Wolfie

Reputation: 1381

I usually split my types depending upon if they are more global or local. For example, if I have some types that are only used within a single module or file, I will tend to store those types in the same place as the implementation:

/components
  /Search
    /Search.tsx
    /search.types.ts <- contains component types like props
    /SearchContainer.tsx

For more global types, I have a separate /types folder, usually at the root level that I split into separate namespaces.

/types
  /search
  /authentication
  /actions
  /routing

What you store in this types directory will be specific to your application, but you get the general idea. You can also use aliasing to import types so that you don't have to deal with relative imports up many levels: ../../../types/something => @types/something

Upvotes: 3

Related Questions