静的型付け
var x:number = 10;
x = "hello";
コンパイルエラーとなります。
var x:number = 10;
x = "hello";
様々な型
// number, string boolean, any
var i = 10;
var x; // var x: any
var results: number[]
results = [10, 5, 3]
列挙型
enum Signal {
Red = 0,
Blue = 1,
Yellow = 2
}
var result: Signal;
// if (result === Signal.Yellow){}
// if (result === Signal['Yellow']){}
console.log(Signal[2])
関数宣言
function add(a: number, b?: number): number {
if (b){
return a + b;
} else{
return a + a;
}
}
console.log(add(5, 3));
関数式
var add = (a: number, b: number): number =>{
return a + b;
}
var add = (a: number, b: number): number => a + b
console.log(add(5, 3));
関数のオーバーロード
function add(a: number, b: number): number; //シグネチャ
function add(a: string, b: string): string;
function add(a: any, b: any): any {
if(typeof a === "string" && typeof b === "string"){
return a + " " + b;
}
return a + b;
}
console.log(add(5, 3));
console.log(add("hello", "world"));
class
class User {
name: string;
constructor(name: string){
this.name = name;
}
sayHi(); void {
console.log("hi! i am " + this.name);
}
}
var tom = new User("tom");
console.log(tom.name);
tom.sayHi();
getter, setter
class User {
name: string;
constructor(private _name: string){
this.name = name;
}
sayHi(); void {
console.log("hi! i am " + this.name);
}
get name(){
return this._name;
}
set name(newValue: string){
this._name = newValue;
}
}
extends, override
class User {
name: string;
constructor(private _name: string){
this.name = name;
}
sayHi(); void {
console.log("hi! i am " + this.name);
}
}
class AdminUser extends User{
private _age: number;
constructor(_name: string, _age: number){
super(_name);
this._age = _age;
}
public sayHi(): void {
console.log("my age:" + this._age);
super.sayHi();
}
}
private:メソッドの中のみ可能
protected:クラスの中のみアクセス可能
静的メンバ:static
class User {
name: string;
constructor(private _name: string){
this.name = name;
User.count++;
}
sayHi(); void {
console.log("hi! i am " + this.name);
}
static count: number = 0;
}
インターフェイス
interface Result {
a: number;
b: number;
}
function getTotal(result: {a: number; b: number}){
return result.a + result.b;
}
var result = {
a: 32,
b: 58
};
console.log(getTotal(result));
interfaceの継承
interface SpringResult {
a: number;
}
interface FallResult{
b: number;
}
interface FinalResult extends SpringResult, FallResult {
final?: number;
}
ジェネリクス
function getArray<T>(value: T): T[]{
return[value, value, value];
}
console.log(getArray<number>(3));
console.log(getArray<string>("hello"));
ジェネリクスの制約
interface Result {
a: number;
b: number;
}
class MyData<T extends Result>{
constructor(public value: T){}
getArray(): T[]{
return [this.value, this.value, this.value];
}
}
内部モジュール
module UserModule{
export var name = "yamada";
export modlue AddressModlue {
var zip = "123-4567"
}
}
console.log(UserModule.name);
console.log(UserModlue.AddressModlue.zip);