[TypeScript]インターフェース(interface)を実装する

2021年11月7日

システム情報
Windows10 64bit
TypeScript Version 4.4.4
構文
class クラス名 implements インターフェース名{
public 変数名:データ型;
使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
//インターフェースEmpの定義
interface Emp {
username:string;
age:number;
addr:string;
//関数の定義
getUsername():string;
getAge():number;
getAddr():string;
}
//インターフェースEmpの実装
class User implements Emp{
public username:string;
public age:number;
public addr:string;
//コンストラクタの定義
constructor(_username:string, _age:number,_addr:string){
this.username = _username;
this.age = _age;
this.addr = _addr;
}
// getメソッドの定義
public getUsername(){ return this.username; }
public getAge(){ return this.age; }
public getAddr(){ return this.addr; }
}
//Userクラスのインスタンスの生成
const cft:User = new User('山田太郎', 34,'東京');
console.log("名前: "+cft.getUsername());
console.log("年齢: "+ cft.getAge());
console.log("住所: "+ cft.getAddr());
//インターフェースEmpの定義 interface Emp { username:string; age:number; addr:string; //関数の定義 getUsername():string; getAge():number; getAddr():string; } //インターフェースEmpの実装 class User implements Emp{ public username:string; public age:number; public addr:string; //コンストラクタの定義 constructor(_username:string, _age:number,_addr:string){ this.username = _username; this.age = _age; this.addr = _addr; } // getメソッドの定義 public getUsername(){ return this.username; } public getAge(){ return this.age; } public getAddr(){ return this.addr; } } //Userクラスのインスタンスの生成 const cft:User = new User('山田太郎', 34,'東京'); console.log("名前: "+cft.getUsername()); console.log("年齢: "+ cft.getAge()); console.log("住所: "+ cft.getAddr());
//インターフェースEmpの定義
interface Emp {
      username:string;
      age:number;
      addr:string;
      //関数の定義
      getUsername():string;
      getAge():number;
      getAddr():string;
 }
 //インターフェースEmpの実装
 class User implements Emp{
 
      public username:string;
    public age:number;
      public addr:string;
    //コンストラクタの定義
      constructor(_username:string, _age:number,_addr:string){
            this.username = _username;
            this.age = _age;
            this.addr = _addr;
    }
    // getメソッドの定義
      public getUsername(){ return this.username; }
      public getAge(){ return this.age; }
      public getAddr(){ return this.addr; }
}
//Userクラスのインスタンスの生成
const cft:User = new User('山田太郎', 34,'東京');
 
console.log("名前: "+cft.getUsername());
console.log("年齢: "+ cft.getAge()); 
console.log("住所: "+ cft.getAddr());

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
名前: 山田太郎
年齢: 34
住所: 東京
名前: 山田太郎 年齢: 34 住所: 東京
名前: 山田太郎
年齢: 34
住所: 東京

 

TypeScript

Posted by arkgame