mikeb
mikeb

Reputation: 11309

create-react-app with typescript - how to put types in separate file

I'm using CRA with typescript (create-react-app myapp --typescript)

I have some typescript stuff in my App.tsx that I would like to store externally, and I've tried creating App.d.ts, index.d.ts, module.d.ts and none of it works.

Here's the interface I'm using:

declare interface IArgs {
    home: string,
    away: string
}

What do I need to do to be able to declare all my Typescript stuff in a file that my source files can share?

Upvotes: 4

Views: 2979

Answers (2)

Abderazak Amiar
Abderazak Amiar

Reputation: 808

You can also create a separated file like App.types.ts and put your types there. e.g.

export type CounterPropsTypes = {
  count: number
  handleIncrement?: () => void
  handleDecrement?: () => void
}

Then import your types like this :

import { CounterPropsTypes } from './App.types'

Finally use your types :

export const Counter = (props: CounterPropsTypes) => {
  return (
    <div>
      <h1>Counter Two</h1>
      <p>{props.count}</p>
      {props.handleIncrement && (
        <button onClick={props.handleIncrement}>Increment</button>
      )}
      {props.handleDecrement && (
        <button onClick={props.handleDecrement}>Decrement</button>
      )}
    </div>
  )
}

Upvotes: 0

jepek
jepek

Reputation: 420

Put in external file eg. interfaces/interfaces.ts:

export interface IArgs {
    home: string,
    away: string
}

Then in App.tsx where you want to use it you import it by: import { IArgs } from 'interfaces/interfaces'; and use it for your needs.

Upvotes: 4

Related Questions