DEV Community

Franz Wong
Franz Wong

Posted on

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)