TypeScript - 表示类型/构造函数与类型

时间:2018-04-05 13:04:00

标签: typescript

类型

我们可以使用类型别名来表达,我们希望将类型作为参数传递,如下所示:

type Type<T> = {
    readonly prototype: T
}

function getTypeArg<T>(t: Type<T>): void {
    ...
}

这会失败,因为123是基元/实例,因此没有原型属性。

getTypeArg(123);

这是因为它是一个类型,因此具有原型属性。

getTypeArg(Number);

实例

对于实例来说同样不容易。

function getInstance(inst: any): void {
    ...
}

允许传递任何实例

getInstance(123);
getInstance("Hello World");

但这也允许传递类型,我们不想要

getInstance(String);

我们应该可以使用类型别名

来解决这个问题
type Instance = {
    constructor: Function;
}

function getInstance(inst: Instance): void {
    ...
}

但这不起作用,所以问题是,为什么?

1 个答案:

答案 0 :(得分:5)

术语说明:你所谓的“类型”最好被描述为“构造函数”。单词“type”有很多含义,在TypeScript中,你通常会用它来表示根本不存在作为运行时值的东西。我认为最好使用“构造函数”。

无论如何,它不起作用的原因是因为所有对象都有constructor属性,甚至是构造函数:

console.log(String.constructor === Function) // true

我认为只有nullundefined无法与您的Instance界面匹配。如果你真的打算排除构造函数,最好将Instance定义为“没有prototype的东西”,如下所示:

type Instance = {
  constructor: Function;
  prototype?: never;  // prototype can be missing or undefined, that's it    
}

它应该更符合您的意图:

getInstance(123); // okay
getInstance("Hello World"); // okay
getInstance(String); // error as desired
getInstance(null); // error as desired I hope
getInstance(undefined); // error as desired I hope

希望有所帮助;祝你好运。