DEV Community

Discussion on: My confusions about TypeScript

 
kenbellows profile image
Ken Bellows

Oh man yes it does, that's exactly what I was looking for! I didn't realize that was a thing! Thanks!

Thread Thread
 
coly010 profile image
Colum Ferry

Or even better using generics:

function handleRelations<T extends Model>(modelClass: T) {
    return modelClass;
}
Thread Thread
 
nickytonline profile image
Nick Taylor

Generics for sure, but it still needs to be typeof Model as he doesn’t want an instance of the class.

Thread Thread
 
coly010 profile image
Colum Ferry

I missed that. In that case, he shouldn't use a class here, rather:

export type Model = {...}

// Or

export interface Model {...}
Thread Thread
 
nickytonline profile image
Nick Taylor • Edited

I rarely use classes aside from React components (pre-hooks) as I prefer functions even though I'm not a full FP kind of person, but they are still used by many. 😉

For sure, a type is an option. It just depends on what he wants to do in that function. If an interface or type is used and he wanted to create an instance of the Model class, using an interface or type would not work. If he wanted to use it for duck typing in his function, then an interface or type would suffice.

interface SomeModelInterface {
    someMethod: () => boolean;
}

class Model implements SomeModelInterface {
    someMethod() {
        return true;
    }
}

function handleRelations(modelClass: typeof Model) {
    const instance = new modelClass();
    const value = instance.someMethod(); // true;
}

function handleRelations2(modelClass: SomeModelInterface) {
    const instance = new modelClass(); // errors
    const value = modelClass.someMethod(); // All good
}

TypeScript playground snapshot

Here's a sample TypeScript Playground for those interested.

Thread Thread
 
coly010 profile image
Colum Ferry

Very interesting. I didn't realise you could combine new with typeof T params.

Thread Thread
 
kenbellows profile image
Ken Bellows

Yeah Model isn't my class, it's provided by Objection.js, an ORM library I'm using. As mentioned in the post, I need to access static properties of various subclasses of Model, so I need to pass around the classes themselves.