런타임에 개체의 클래스 이름 가져오기
실행 시 TypeScript를 사용하여 객체의 클래스/타입 이름을 가져올 수 있습니까?
class MyClass{}
var instance = new MyClass();
console.log(instance.????); // Should output "MyClass"
간단한 답변:
class MyClass {}
const instance = new MyClass();
console.log(instance.constructor.name); // MyClass
console.log(MyClass.name); // MyClass
단, 최소화된 코드를 사용할 때는 이름이 다를 수 있으므로 주의하십시오.
나의 해결책은 학급 이름에 의존하지 않는 것이었다.object.constructor.name은 이론상으로는 기능합니다.그러나 Ionic과 같은 환경에서 TypeScript를 사용하는 경우, Ionic의 프로덕션 모드는 Javascript 코드를 최소화하므로 프로덕션으로 들어가자마자 불꽃이 튀게 됩니다.그래서 그 수업들은 "a"와 "e"와 같은 것으로 이름이 붙여진다.
결과적으로 컨스트럭터가 클래스 이름을 할당하는 모든 오브젝트에 typeName 클래스를 갖게 되었습니다.그래서:
export class Person {
id: number;
name: string;
typeName: string;
constructor() {
typeName = "Person";
}
네, 그건 부탁받은 게 아니에요.하지만 앞으로 더 작아질 수 있는 것에 대해 constructor.name을 사용하는 것은 단지 두통을 호소하는 것일 뿐입니다.
파티에 늦은 건 알지만 이것도 효과가 있는 것 같아요.
var constructorString: string = this.constructor.toString();
var className: string = constructorString.match(/\w+/g)[1];
아니면...
var className: string = this.constructor.toString().match(/\w+/g)[1];
위의 코드는 전체 생성자 코드를 문자열로 가져오고 정규식을 적용하여 모든 'words'를 가져옵니다.첫 번째 단어는 '함수'이고 두 번째 단어는 수업 이름이어야 합니다.
이게 도움이 됐으면 좋겠다.
먼저 인스턴스를 다음 주소로 캐스트해야 합니다.any
왜냐면Function
의 유형 정의에는 다음이 없습니다.name
소유물.
class MyClass {
getName() {
return (<any>this).constructor.name;
// OR return (this as any).constructor.name;
}
}
// From outside the class:
var className = (<any>new MyClass()).constructor.name;
// OR var className = (new MyClass() as any).constructor.name;
console.log(className); // Should output "MyClass"
// From inside the class:
var instance = new MyClass();
console.log(instance.getName()); // Should output "MyClass"
업데이트:
TypeScript 2.4(및 그 이전 버전)에서는 코드를 보다 깔끔하게 만들 수 있습니다.
class MyClass {
getName() {
return this.constructor.name;
}
}
// From outside the class:
var className = (new MyClass).constructor.name;
console.log(className); // Should output "MyClass"
// From inside the class:
var instance = new MyClass();
console.log(instance.getName()); // Should output "MyClass"
이 질문을 보세요.
TypeScript는 JavaScript로 컴파일되므로 실행 시 JavaScript를 실행하므로 동일한 규칙이 적용됩니다.
최소화/업그레이션에서 살아남는 데코레이터를 사용한 솔루션
코드 생성을 사용하여 다음과 같은 메타데이터로 엔티티 클래스를 꾸밉니다.
@name('Customer')
export class Customer {
public custId: string;
public name: string;
}
다음으로 다음 도우미와 함께 사용합니다.
export const nameKey = Symbol('name');
/**
* To perserve class name though mangling.
* @example
* @name('Customer')
* class Customer {}
* @param className
*/
export function name(className: string): ClassDecorator {
return (Reflect as any).metadata(nameKey, className);
}
/**
* @example
* const type = Customer;
* getName(type); // 'Customer'
* @param type
*/
export function getName(type: Function): string {
return (Reflect as any).getMetadata(nameKey, type);
}
/**
* @example
* const instance = new Customer();
* getInstanceName(instance); // 'Customer'
* @param instance
*/
export function getInstanceName(instance: Object): string {
return (Reflect as any).getMetadata(nameKey, instance.constructor);
}
추가 정보:
- 를 인스톨 할 필요가 있는 경우가 있습니다.
reflect-metadata
제안된 ES7 Reflection API를 위해 TypeScript 멤버에 의해 작성된 pollyfill입니다.- JS의 데코레이터에 대한 제안은 여기에서 추적할 수 있습니다.
- 다음을 사용하려면 ".protype"을 추가해야 합니다.
myClass.prototype.constructor.name
. - 그 이외의 경우는, 다음의 코드를 사용합니다.
myClass.constructor.name
TypeScript 오류가 발생했습니다.
error TS2339: Property 'name' does not exist on type 'Function'
.
Angular2에서는 컴포넌트명을 취득하는데 도움이 됩니다.
getName() {
let comp:any = this.constructor;
return comp.name;
}
comp:any가 필요합니다.이는 TypeScript 컴파일러가 처음에 함수에는 속성 이름이 없기 때문에 오류를 발생시키기 때문입니다.
완전한 TypeScript 코드
public getClassName() {
var funcNameRegex = /function (.{1,})\(/;
var results = (funcNameRegex).exec(this["constructor"].toString());
return (results && results.length > 1) ? results[1] : "";
}
예상되는 유형을 이미 알고 있는 경우(예를 들어 메서드가 유니언 유형을 반환하는 경우) 유형 가드를 사용할 수 있습니다.
예를 들어, 프리미티브 유형의 경우 다음과 같은 가드 유형을 사용할 수 있습니다.
if (typeof thing === "number") {
// Do stuff
}
복잡한 유형의 경우 다음과 같이 가드 인스턴스를 사용할 수 있습니다.
if (thing instanceof Array) {
// Do stuff
}
언급URL : https://stackoverflow.com/questions/13613524/get-an-objects-class-name-at-runtime
'programing' 카테고리의 다른 글
where 절에서 'case expression column' 사용 (0) | 2023.04.04 |
---|---|
Woocommerce에서 '품절' 제품 숨기기 (0) | 2023.04.04 |
각도로 문자열 길이 제한JS (0) | 2023.04.04 |
Woocommace mySQL 쿼리 - 모든 주문, 사용자 및 구매한 아이템 나열 (0) | 2023.04.04 |
HTML5 다중 파일 업로드: AJAX를 통해 하나씩 업로드 (0) | 2023.04.04 |