我可能错过了什么,但我尝试使用ClassConstructor从class-transformer和我有一个问题
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错误吗?
发布于 2022-11-29 01:46:53
这里的问题是,T通常将由type参数的类型确定,请考虑以下几点:
import { ClassConstructor } from 'class-transformer'
class A { a = 1; b = "" }
class B { a = ""; b = 1 }
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
}
return []
}当您在这样的函数调用上悬停时:
myFunction(A) 您将看到它正确地选择了返回类型的A[]。
或者,如果您正在arrayOfA上操作,并且需要将其键入为A[],则可以在返回它之前将其强制发送给T[]:
const myFunction = <T extends Types>(type: ClassConstructor<T>): T[] => {
if (type === A) {
const arrayOfA: A[] = []
doSomethingWithAValues(arrayOfA);
return arrayOfA as T[]
}
return []
}https://stackoverflow.com/questions/74607593
复制相似问题