简体   繁体   中英

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:

  • declare all the custom types in a common file and import that wherever necessary?
  • declare custom types in their related files and make the web of imports/exports?
  • some other option that didn't yet cross my mind?

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).

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

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM