aviya.developer
aviya.developer

Reputation: 3613

How to define a TS type/interface/etc. which is accessible via multiple files?

I would like to reuse a specific custom type i made in different files across my app, yet I have not quite managed to find a proper resource explaining how to do so.

src/sharedTypes.ts
src/file1.ts
src/file2.ts

sharedTypes.ts:

type MyPoint = {
   x: number;
   y: number;
}

I would like to be able to use this MyPoint type when working on file1.ts or file2.ts.

for instance:

const pointLog = (point: MyPoint): void => {
    console.log(`Point is located at: ${point.x}, ${point.y}.`);
}

pointLog({x:2, y:4});

Thanks!

Upvotes: 2

Views: 39

Answers (1)

CharybdeBE
CharybdeBE

Reputation: 1843

Use the export keyword

eg

 export type MyPoint = {
    x: number;
   y: number;
}

and then the import in the other file

 import { MyPoint } from './sharedTypes';
 const pointLog = (point: MyPoint): void => {
     console.log(`Point is located at: ${point.x}, ${point.y}.`);
 }

 pointLog({x:2, y:4});

Upvotes: 2

Related Questions