How to use TypeScript for Basic

A TypeScript is open source programming language which was developed by MicroSoft. It is styped superset of JavaScrpt, you can use optional typing static typing and inference. Many IDE support it and also TypeScript supported to ES6, ES7, anytning version. The TypeScript rapid growth and use.

Setup

The TypeScript depend on Node.js So you have to install Node.js.

$ npm install -g typescript

If you finished install TypeScript, you can use tsc command.

$ tsc -h

Then, TypeScript needs transpiling, to convert to JavaScript. You can transpile for tsc command, like this.

$ tsc index.ts
$ cat index.js

Also, You can transpile when you rewrite code, use --watch option.

$ tsc index.ts --watch

Variable Type

The TypeScript assign to type for variable. If you wanna use type, assign afeter variable and with colon(:).

let isBeginner: boolean = true;
let total: number = 0;
let name: string = 'Vishwas';

As well, you can use a template literal.

let name: string = 'JavaScript';
let sentence: string = `Hello ${name} World`;

Void

And also, null and undefined types, you can assign variable. The bellow code is working.

let n: null = null;
let u: undefined = undefined;
let v: void = undefined;

let isNew: boolean = null;
let myName: string = undefined;

Array

You can use also array types. The array can define familer syntax for variable.

let list1: number[] = [1,2,3];
let list2: Array<number> = [1,2,3];

let person1: [string, number] = ['Chris', 22];

Object

object is a type that represents the non-primitive type. With object type, APIs like Object.create can be better represented.

declare function create(o: object | null): void;
create({ prop: 0 }); // OK
create(null); // OK

create(42); // Error
create("string"); // Error
create(false); // Error
create(undefined); // Error

enum

If you wanna get key of value, you can use enum keyword. The enums allow us to declare a set of named constants i.e. a collection of related values that can be numeric or string values.

enum Color {Red, Green, Blue};
let c: Color = Color.Green;
console.log(c);

enum Color {Red = 5, Green, Blue};
let c: Color = Color.Green;
console.log(c);

Any

The any type can put the antying type, If you didin’t assign type yet, you can use useful.

let myVariable: any = 10;

let anyType: any;
anyType = 20;
anyType = true;

関連記事