【问题标题】:ts(2322) Typescript genericsts(2322) Typescript 泛型
【发布时间】:2022-11-29 10:08:27
【问题描述】:
我可能遗漏了一些东西,但我尝试使用 class-transformer 中的 ClassConstructor,但我遇到了问题
import { ClassConstructor } from 'class-transformer'
class A {}
type Types = A
const myFunction = <T extends Types>(type: ClassConstructor<T>): T[] => {
if (type === A) {
const arrayOfA: A[] = []
return arrayOfA
}
return []
}
这样做之后,对于return arrayOfA,打字稿告诉我:
Type 'A[]' is not assignable to type 'T[]'.
Type 'A' is not assignable to type 'T'.
'A' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'A'.ts(2322)
这是class-transformer的功能
export declare type ClassConstructor<T> = {
new (...args: any[]): T;
};
有人有想法替换ClassConstructor 或解决此different subtype of constraint 错误吗?
【问题讨论】:
标签:
typescript
typescript-generics
class-transformer
【解决方案1】:
这里的问题是 T 通常由 type 参数的类型决定考虑以下因素:
import { ClassConstructor } from 'class-transformer'
class A { a: int, b: string }
class B { a: string, b: int }
class C {}
type Types = A | B
const myFunction = <T extends Types>(type: ClassConstructor<T>): T[] => {
return []
}
myFunction(A) // returns A[]
myFunction(B) // returns B[]
myFunction(C) // doesn't compile
所以发生在你身上的是打字稿没有接受这个条件的含义:if (type === A)。假设 Types 是在您的代码中定义的,就像我上面的代码一样。因为它不理解条件的含义,就好像你在做:
type Types = A | B
const myFunction = <T extends Types>(type: ClassConstructor<T>): T[] => {
const arrayOfA: A[] = []
return arrayOfA
}
由于 T 可以像 A 一样容易地成为 B,并且 A 和 B 不兼容,因此可以理解地抱怨。
解决方法很简单,把arrayOfA的类型改成T[]即可:
const myFunction = <T extends Types>(type: ClassConstructor<T>): T[] => {
if (type === A) {
const arrayOfA: T[] = []
return arrayOfA as T]
}
return []
}
当您将鼠标悬停在这样的函数调用上时:
myFunction(A)
您会看到它已正确获取返回类型 A[]