在运行时使用反射确定Typescript属性类型

jos*_*erk 6 reflection typescript typescript2.0

将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();
Run Code Online (Sandbox Code Playgroud)

日志输出“对象”,“数组”和:

Object {
    configurable: true,
    enumerable: true,
    value: [],
    writeable: true
}
Run Code Online (Sandbox Code Playgroud)

我想遍历Author的属性,并确定Author.books的类型或任何属性。我希望能够在运行时确定Author.booksBooks数组。仅仅知道它是一个对象或数组对我要实现的目标毫无帮助。

有什么想法可以实现吗?

Mei*_*hes 4

我将冒险回答并说它不能用默认情况下可用的内容来完成 - 您需要解析d.ts以获取所有类型的真实反映。

正如你所说; 该数组是 的实例,推断数组应该包含什么类型的Array唯一方法是传递所需类型的类。所以,你可以这样做:

class Book {
  public title: string;
  public isbn: string;
}

type Newable<T> = {
  new (): T;
}

class Author<T> {
  public name: string = '';
  public books: T[] = [];

  constructor(bookRef: Newable<T>) {
    console.log(`name: ${bookRef.name}`);
  }
}

const author = new Author(Book);
Run Code Online (Sandbox Code Playgroud)

并不奇怪,而且只有当 Book 是一类时它才有效。

typescript 还可以根据传递给构造函数的内容推断出 Book 使用的类型:

在此输入图像描述

bookRef.name将在运行时为您提供类名。