打字稿:键入一个分配了类型的变量

时间:2016-08-05 18:52:18

标签: typescript

有关于输入将为其指定类型的变量的问题。

EG:

interface HTTPClient { … }
class BrowserHTTPClient implements HTTPClient { … }
class NodeHTTPClient implements HTTPClient { … }

let HTTPClientType: ********;

if (typeof window === 'undefined') {
  HTTPClientType = NodeHTTPClient;
} else {
  HTTPClientType = BrowserHTTPClient;
}

我试图找出是否有办法将变量键入类型。我没有在Typescript文档中看到这一点。

我用什么替换*******,打字稿是否支持,我是否需要建立工厂?

2 个答案:

答案 0 :(得分:2)

如果我理解你的问题,你可以这样做:

let httpClientType: typeof BrowserHTTPClient | typeof NodeHTTPClient;

if (typeof window === 'undefined') {
  httpClientType = NodeHTTPClient;
} else {
  httpClientType = BrowserHTTPClient;
}

var httpClient = new httpClientType();

<强>澄清

class BrowserHTTPClient {  }

// myObject should be of the type BrowserHTTPClient
// For example an instance of BrowserHTTPClient, but not necessarily as long as it's structurally compatible with the type BrowserHTTPClient
let myObj: BrowserHTTPClient;

// myClass should be the class BrowserHTTPClient (Or rather, it should fulfill the type of the class of the type BrowserHTTPClient, hence it can be any object that has the same structure as the _class_ BrowserHTTPClient. Inception warning here, see explanation of structural typing below.)
let myClass: typeof BrowserHTTPClient;

// make a instance of myClass (BrowserHTTPClient)
myClass = BrowserHTTPClient; // Here, myClass IS the class BrowserHTTPClient.
myObj = new myClass();

类与类型

在像C#这样的主格式语言中,classtype实际上是相同的。如果你说变量属于某种类型,那么变量不能是该特定类的实例,或者,如果类型来自接口,则是实现该特定接口的类。

在结构类型的TypeScript中,这是不同的,概念classtype更加分开。如果在typescript中定义一个类,那么也会创建一个类。但是,当您将变量定义为该类型时,可以将其设置为满足该类型的任何变量。

class MyClass {
    public Name: string;
}

class MyOtherClass {
    public Name: string;
    public Age: number;
}

let obj: MyClass;

obj = new MyClass();
obj = new MyOtherClass(); // Also ok, since it fulfills the type MyClass (It has a field Name that is a string)

答案 1 :(得分:0)

一种选择是通过构造函数接口创建工厂:

export interface HTTPClientConstructor {
  new(baseUrl: string): HTTPClient;
}
interface HTTPClient { … }
class BrowserHTTPClient implements HTTPClient { … }
class NodeHTTPClient implements HTTPClient { … }

let HTTPClientFactory: HTTPClientConstructor;

if (typeof window === 'undefined') {
  HTTPClientFactory = NodeHTTPClient;
} else {
  HTTPClientFactory = BrowserHTTPClient;
}