簡體   English   中英

推斷TypeScript泛型類類型

[英]Infer TypeScript generic class type

B擴展了泛型類A.我需要能夠推斷B的擴展A的泛型類型。請參閱下面的代碼。

我在以前的Typescript版本中成功使用了這個,但對於我當前使用3.2.4的項目(也嘗試過最新的3.4.5),推斷類型似乎導致{}而不是string

知道我做錯了什么嗎? 這不可能改變?

class A<T> {

}

class B extends A<string> {

}

type GenericOf<T> = T extends A<infer X> ? X : never;

type t = GenericOf<B>; // results in {}, expected string

經過大量的研究,好的nvm自己想出來了。 似乎TypeScript無法在這種簡單的情況下區分,因為這些類都是空的並且等同於{} 添加屬性實際上不夠,它需要是實際引用泛型T屬性,以便TypeScript在以后正確地推斷泛型類型:



class A<T> {
  constructor(public a: T) {}
}

class B extends A<C> {
  constructor(public b: C) {
    super(b);
  }
}

class C {
  constructor(public c: string) {
  }
}

type GenericOf<T> = T extends A<infer X> ? X : never;

type t = GenericOf<B>;

目前,具有未在類中使用的泛型的類具有與{}相同的“結構”,因此推斷。 所做的更改破壞了您的功能是一個錯誤修復,解決方法是在類中的某個地方使用“A”通用,推理將再次起作用。

希望這可以幫助。

class A<T> {
    hello: T = "" as any; // note that i have used the generic somewhere in the class body.
}
class B extends A<string> {}
type GenericOf<T> = T extends A<infer X> ? X : never;
type t = GenericOf<B>; // string.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM