내가 제대로 질문을 이해한다면, 당신이 할 수있는 :
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();
클래스 vs 유형
C#과 같은 공인 입력 언어의 경우 class
과 type
은 사실상 같습니다. 변수가 어떤 타입이라고 말하면, 그 변수는 그 특정 클래스의 인스턴스가 아닌 다른 것일 수도 있고, 타입이 인터페이스에서 오는 것이라면, 그 특정 인터페이스를 구현하는 클래스 일 수도 있습니다.
구조적으로 형식화 된 TypeScript에서는 같지 않으며 개념 class
과 type
은 더 멀리 있습니다. 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)
어떻게'HTTPClientType'을 사용할 예정입니까? 원하는 유형이나 수업입니까? – Alex
유형이므로 많은 인스턴스를 만들 수 있습니다. – squirly
인스턴스를 만들려면 유형이 아닌 클래스가 필요합니다. – Alex