作者:陈俊凯660638 | 来源:互联网 | 2023-02-04 15:33
将TypeScript转换为Javascript时,我的理解是TypeScript类型信息会丢失,并且诸如反射之类的功能只能以非常有限的方式工作。我们在运行时使用Javascript反射,这可以理解地限制了有关TypeScript类型的“知识”。
是否可以在运行时检索TypeScript类型信息?
让我们看一下codepen.io上的以下代码片段:
class Book {
public title: string;
public isbn: string;
}
class Author {
public name: string = '';
public books: Book[] = [];
constructor() {
const r = Reflect.getOwnPropertyDescriptor(this, 'books');
console.log(`typeof: ${typeof this.books}`);
console.log(`constructor: ${this.books.constructor.name}`);
console.log(r);
}
}
const author = new Author();
日志输出“对象”,“数组”和:
Object {
configurable: true,
enumerable: true,
value: [],
writeable: true
}
我想遍历Author的属性,并确定Author.books的类型或任何属性。我希望能够在运行时确定Author.books是Books数组。仅仅知道它是一个对象或数组对我要实现的目标毫无帮助。
有什么想法可以实现吗?