TypeScript: JavaScript With Syntax For Types.

Apply types to your JavaScript project incrementally, each step improves editor support and improves your codebase.

Let's take this incorrect JavaScript code, and see how TypeScript can catch mistakes in your editor.

jsfunctioncompact(arr) {if (orr.length > 10)returnarr.trim(0, 10)returnarr}

No editor warnings in JavaScript filesThis code crashes at runtime!

JavaScript file

js// @ts-check functioncompact(arr) {if (orr.length > 10)Cannot find name 'orr'.2304Cannot find name 'orr'.returnarr.trim(0, 10)returnarr}

Adding this to a JS file shows errors in your editor

the param is arr, not orr!

JavaScript with TS Check

js// @ts-check /** @param{any[]}arr */functioncompact(arr) {if (arr.length > 10)returnarr.trim(0, 10)Property 'trim' does not exist on type 'any[]'.2339Property 'trim' does not exist on type 'any[]'.returnarr }

Using JSDoc to give type information

Now TS has found a bad call. Arrays have slice, not trim.

JavaScript with JSDoc

tsfunctioncompact(arr: string[]) {if (arr.length > 10)returnarr.slice(0, 10)returnarr}

TypeScript adds natural syntax for providing types

TypeScript file

Tag » What Is A Ts File