[TypeScript] 基礎

型指定

var onigiri: string = 'onigiri',
	calories: number = 200;

function todaysMeal(food: string, energy: number): string {
	return `my ${food} has ${energy} calories`
}

todaysMeal(onigiri, calories)

インターフェイス
L オブジェクトがある構造に合っているかの型チェックに使用

interface Person {
	name: string;
	age: number;
}

function intro(person:Person): string {
	return `My name is ${person.name}. I am ${person.age}`
}

var ken = {
	name: 'Ken',
	age: 20
}

intro(ken)

クラス

class Menu {
	items: Array<string>;
	pages: number

	constructor(item_list: Array<string>, total_pages: number){
		this.items = item_list;
		this.pages = total_pages;
	}

	list(): void {
		console.log("out menu for today:");
		for (var i=0; i<this.items.length; i++){
		console.log(this.items[i]);
		}
	}
}

var sundayMenu = new Menu(["pancakes","waffles","orange juice"], 1);

sundayMenu.list();

$ node hello.js
out menu for today:
pancakes
waffles
orange juice

なるほど、型付言語だとGoと近いな