typescript interfaceを使用する

typescript interfaceを使用する

typescriptで、interfaceを使用するサンプルコード記述してます。typescriptのバージョンはVersion 4.1.2となります。

環境

  • OS windows10 64bit
  • typescript Version 4.1.2

interfaceを使用

typescriptでは、以下のようにしてinterfaceを使用することが可能です。

interface hoge {
    num: number;
    str: string;
}

const h: hoge = { num: 10, str: 'mebee' }

console.log(h.num) // 10

console.log(h.str) // mebee

「?」を付けて、省略することも可能です。

interface hoge {
    num: number;
    str?: string;
}

const h: hoge = { num: 10 }

console.log(h.num) // 10

const h2: hoge = { num: 10, str: 'mebee' }

console.log(h2.num) // 10
console.log(h2.str) // mebee

関数も定義することが可能です。

interface hoge {
    (num: number): number;
}

const h: hoge = (num) => num + num;


console.log(h(1)) // 2

また、interfaceで設計にされたクラスを実装することも可能です。

interface iperson {
	name:string;
	Age:number;
	getName():string;
	getAge():number;
 }

 class person implements iperson{

	public name:string;
    public Age:number;
    
	constructor(_name:string, _Age:number){
		this.name = _name;
		this.Age = _Age;
    }
    
	public getName(){ return this.name; }
	public getAge(){ return this.Age; }
}

const p:person = new person('tom', 20);

console.log( p.getName()); // tom
console.log( p.getAge()); // 20