lundi 8 mai 2017

Determine Typescript property type with reflection at runtime

When transpiling TypeScript to JavaScript, my understanding is that TypeScript type information is lost and features like reflection will only work in a very limited manner. We're using JavaScript reflection at runtime, which understandably has limited "knowledge" about TypeScript types.

Could there be a way to retrieve TypeScript type information at runtime?

Let's take the following snippet, available on 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 output "object", "Array" and:

Object {
    configurable: true,
    enumerable: true,
    value: [],
    writeable: true
}

I want to iterate over the properties of Author, and determine the type of Author.books or any property. I am expecting to be able to establish at runtime that, Author.books is an Array of Books. Simply knowing that it is an object or an array does not help with what I am trying to achieve at all.

Any ideas how this could be achieved?





Aucun commentaire:

Enregistrer un commentaire