After transpiling TypeScript code to JavaScript, it is commonly understood that TypeScript type information gets lost and features such as reflection become very restricted. Since we rely on JavaScript reflection at runtime, the level of understanding regarding TypeScript types is understandably limited.
Is there a way to access TypeScript type information during runtime?
Consider the following code snippet from 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();
The logs display "object", "Array" and:
Object {
configurable: true,
enumerable: true,
value: [],
writeable: true
}
The goal is to loop through Author properties and determine the type of Author.books or any other property dynamically. The aim is to be able to recognize that Author.books is an Array of Books during runtime. Merely identifying it as an object or array does not fully serve this purpose at all.
Does anyone have any suggestions on how this can be accomplished?