Skip to content

Passing a model to a function and accessing static members #232

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
mikew opened this issue Dec 12, 2017 · 4 comments
Closed

Passing a model to a function and accessing static members #232

mikew opened this issue Dec 12, 2017 · 4 comments

Comments

@mikew
Copy link

mikew commented Dec 12, 2017

I'm trying to write a function that takes a model class and calls .findAll({}), but TypeScript is giving me an error. This reproduces it:

async function createResource(model: typeof Model) {
  const results = await model.findAll({})
}

gives:

The 'this' context of type 'typeof Model' is not assignable to method's 'this' of type 'new () => Model<any>'.
  Cannot assign an abstract constructor type to a non-abstract constructor type.
@mikew
Copy link
Author

mikew commented Dec 12, 2017

Seems this might be a deeper issue in TypeScript: microsoft/TypeScript#5843 (comment)

@RobinBuschmann
Copy link
Member

RobinBuschmann commented Dec 12, 2017

You can achieve this like so:

type NonAbstract<T> = {[P in keyof T]: T[P]}; // "abstract" gets lost here
type Constructor<T> = (new () => T);
type NonAbstractTypeOfModel<T> = Constructor<T> & NonAbstract<typeof Model>;

function createResource<T extends Model<T>>(model: NonAbstractTypeOfModel<T>): Promise<T[]> {
    return model.findAll<T>();
}

Now you can use it without passing any generic type explicitly. The proper type is inferred automatically by typescript:

createResource(User)
    .then(users => users[0]. ...) // <-- autocompletion should work very well here
;

@mikew
Copy link
Author

mikew commented Dec 12, 2017

How obvious, thanks! This solves my issue, but FYI, yours gives:

Type 'Bluebird<T[]>' is not assignable to type 'Promise<T[]>'.
  Property '[Symbol.toStringTag]' is missing in type 'Bluebird<T[]>'.

So you need to return model.findAll<T>() as any as Promise<T[]>.

@mikew mikew closed this as completed Dec 12, 2017
@RobinBuschmann
Copy link
Member

You need to use bluebird as the promise type:
import * as Promise from 'bluebird' Then the error disappears as well :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants