TypeScript: Quick Start & Examples

This post describes how to start programming in TypeScript.


what is TypeScript?

TypeScript = JavaScript + static type definitions


install

You can install it using npm

% node --version

v15.14.0

% npm --version

7.7.6

% npm install -g typescript

% tsc --version

Version 4.2.4


hello world

Create hello.ts as follows:

console.log("Hello, world");

tsc compiles .ts into .js

% tsc hello.ts

% ls 

hello.js hello.ts

% cat hello.js 

console.log("Hello, world");

Run .js with Node.Js:

% node hello.js 

Hello, world

types

The following code shows examples of the static type definitions.

// boolean
let flag: boolean = true;

// number
let n: number;
n = 1;
// n = 'hello'; -> error TS2322: Type 'string' is not assignable to type 'number'.

// string
let str = 'hello'; // type is auto defined if omitted during init
str = 'world';
// str = 2; -> error TS2322: Type 'number' is not assignable to type 'string'.

// void
function sayHello(name: string): void {
  console.log('Hello, ' + name);
}
sayHello('World!');

// Array
let arr: number[] = [1, 2, 3];

// Object
interface Student {
  name: string,
  score: number,
  address?: string, // undefined (makes it optional)
  grade: string | null // nullable
}
let s1: Student = {name: 'Ann', score: 90, address: 'Tokyo', grade: 'A'};
let s2: Student = {name: 'Bob', score: 80, grade: null};

Comments

Popular posts from this blog

Selenide: Quick Start

Minikube Installation for M1 Mac

Three.js Quick Start - Run Spinning-Cube Example