DEV Community

Franz Wong
Franz Wong

Posted on

1 1

Validate Javascript project with Typescript

Interface or contract is important to define the boundary between modules. Typescript helps to validate your code with contract automatically. Changing the whole project from Javascript to Typescript may not be feasible, but you can provide only Typescript definitions.

Let's say I have a project like this.

src/note-service.js

const uuid = require('uuid/v4');

async function addNote(note) {
  // return a string as id
  return uuid();
}

module.exports = {
  addNote,
};

src/main.js

const NoteService = require('./note-service');

async function main() {
  const noteId = await NoteService.addNote({
    content: 'hello world',
  });
  console.log(`note id: ${noteId}`);
}

main();

We can simply add a definition to our Note service. The file name should match the Javascript code file.

src/note-service.d.ts

export type Uuid = string;

export function addNote(note: Note): Promise<Uuid>;

export interface Note {
  content: string,
}

We also need to add Typescript configuration file.

tsconfig.json

{
  "compilerOptions": {
    "outDir": "./built",
    "target": "ES2018",
    "moduleResolution": "node",
    "module": "CommonJS",
    "allowJs": true,
    "checkJs": true
  },
  "include": [
    "./src/**/*"
  ],
  "exclude": [
    "node_modules"
  ]
}

So now we can simply use tsc --noEmit to validate our project.

Top comments (0)

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay