「TypeScript」keyof演算子のサンプル

2022年1月22日

書式
type クラス名 = {
メンバー変数名1:データの型;
メンバー変数名2:データの型;
};
type 変数名 = keyof クラス名
型コンテキストで keyof演算子 を利用するとオブジェクトのプロパティ名を抽出します
使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
//クラスの定義
type Student = {
username: string;
age: number;
};
//オブジェクトのプロパティ名を抽出する
type cft = keyof Student;
let kk: cft;
kk = 'username';
console.log("プロパティ名1: " +kk);
kk = 'age';
console.log("プロパティ名2: " +kk);
//クラスの定義 type Student = { username: string; age: number; }; //オブジェクトのプロパティ名を抽出する type cft = keyof Student; let kk: cft; kk = 'username'; console.log("プロパティ名1: " +kk); kk = 'age'; console.log("プロパティ名2: " +kk);
//クラスの定義
type Student = {
  username: string;
  age: number;
};

//オブジェクトのプロパティ名を抽出する
type cft = keyof Student; 

let kk: cft;
kk = 'username'; 
console.log("プロパティ名1: " +kk);

kk = 'age'; 
console.log("プロパティ名2: " +kk);

実行結果
C:\typescript>tsc
C:\typescript>ts-node arkgame.js
プロパティ名1: username
プロパティ名2: age

TypeScript

Posted by arkgame