TypeScriptでオブジェクトのクラス名を取得する方法
TypeScriptで実行時にオブジェクトのクラス名を取得する方法
constructor.name プロパティを使用する
これは最も単純な方法です。クラスの constructor
プロパティには、クラスの名前が格納されています。
class Person {
constructor(public name: string) {}
}
const person = new Person("John Doe");
const className = person.constructor.name; // "Person"
typeof
演算子を使用して、オブジェクトの型を取得できます。型の名前はクラス名と同じです。
class Person {
constructor(public name: string) {}
}
const person = new Person("John Doe");
const className = typeof person; // "Person"
instanceof
演算子を使用して、オブジェクトが特定のクラスのインスタンスかどうかを確認できます。
class Person {
constructor(public name: string) {}
}
const person = new Person("John Doe");
if (person instanceof Person) {
const className = person.constructor.name; // "Person"
}
Reflect
オブジェクトを使用して、オブジェクトに関するメタ情報を取得できます。
class Person {
constructor(public name: string) {}
}
const person = new Person("John Doe");
const className = Reflect.get(person, "constructor").name; // "Person"
これらの方法のどれを使用するかは、状況によって異なります。最も単純な方法は constructor.name
プロパティを使用する方法ですが、typeof
演算子や instanceof
演算子の方がより柔軟な場合があります。
注意点
- これらの方法は、クラスのインスタンスに対してのみ使用できます。
- クラスの名前は、変更される可能性があります。
TypeScriptで実行時にオブジェクトのクラス名を取得するには、いくつかの方法があります。これらの方法のどれを使用するかは、状況によって異なります。
// クラス定義
class Person {
constructor(public name: string) {}
}
// オブジェクトの作成
const person = new Person("John Doe");
// クラス名の取得
const className1 = person.constructor.name; // "Person"
const className2 = typeof person; // "Person"
const className3 = person instanceof Person ? person.constructor.name : ""; // "Person"
const className4 = Reflect.get(person, "constructor").name; // "Person"
// 出力
console.log(className1); // "Person"
console.log(className2); // "Person"
console.log(className3); // "Person"
console.log(className4); // "Person"
オブジェクトのクラス名を取得するその他の方法
クラス名を直接プロパティとして格納する
クラス名を取得する必要がある場合、クラス名を直接プロパティとして格納することができます。
class Person {
public readonly className = "Person";
constructor(public name: string) {}
}
const person = new Person("John Doe");
const className = person.className; // "Person"
シンボルを使用して、クラス名を表すユニークな識別子を生成することができます。
const classNameSymbol = Symbol("Person");
class Person {
constructor(public name: string) {}
}
const person = new Person("John Doe");
Reflect.defineProperty(person, classNameSymbol, {
value: "Person",
enumerable: false,
configurable: false,
});
const className = Reflect.get(person, classNameSymbol); // "Person"
カスタムユーティリティ関数を作成して、オブジェクトのクラス名を取得することができます。
function getClassName(object: any): string {
if (object.constructor.name) {
return object.constructor.name;
}
return typeof object;
}
const person = new Person("John Doe");
const className = getClassName(person); // "Person"
これらの方法は、特定の状況で役立つ場合があります。
typescript