#Generic return type for array of classes inheriting common class

21 messages · Page 1 of 1 (latest)

lilac rampart
#

I am trying to set the return type on a function.

export const getModels = <T extends new () => Model>(): T[] => [UserDetail];

The return is an array of classes extending from the Model class from sequelize-typescript. But I am getting the error:

Type 'typeof UserDetail' is not assignable to type 'T'. 'typeof UserDetail' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'new () => Model<any, any>'
next marlin
#

T isn't used in the parameter list, this is basically the generic as typecast pattern

#

the generic should probably be on the returned function misread

#

although, you might not even need/want the generic if you want to allow multiple different classes

#

generics in methods aren't very useful if they're only used once

lilac rampart
#

this doesnt work either

next marlin
#

i don't see how that's relevant

#
export const getModels = (): (new () => Model)[] => [UserDetail];
lilac rampart
#

wow.. why does that work?

#

UserDetail is extending model yes but new Userdetail will give instance of userdetail not model. so why does this work and not the generic?

#

the generic logically sounds more accurate. T extends Model and new() returns instance of T.

next marlin
#

your function just isn't meant to be generic

#

generic functions are functions that have unknown typings, where multiple arguments need to follow the same unknown type, or the return type has a type related to an argument

lilac rampart
#

Hm ok. Understood that part. Just wondering why new()=>Model is a correct type for class extending Model.

next marlin
#

for generics in methods, if the generic is only used once, it's likely a mistake to use the generic.

next marlin
lilac rampart
#

ok its a valid type because it inherits Model

#

like that?

next marlin
#

its constructor returns a type that is a subtype of Model

#

ts doesn't really care about inheritance, it cares about the types after inheritance happens