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.

Postgres on Neon - Get the Free Plan

No credit card required. The database you love, on a serverless platform designed to help you build faster.

Get Postgres on Neon

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more