Skip to content
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

Given the type 'T & Document', can't type the object returned by .toObject() as T #9944

Closed
adriano-di-giovanni opened this issue Feb 17, 2021 · 1 comment
Labels
typescript Types or Types-test related issue / Pull Request
Milestone

Comments

@adriano-di-giovanni
Copy link

I don't know if it is a bug. It seems to be so. I can tell you it worked with v5.10.11. It doesn't work anymore with v5.11.16

Given this piece code

function transformOne<T>(document: T & Document): T {
  return document.toObject();
}

the compiler complaints as follows

Type 'Pick<Pick<_LeanDocument<T & Document<any>>, "_id" | "__v" | "id" | Exclude<keyof T, "$ignore" | "$isDefault" | "$isDeleted" | "$isEmpty" | "$isValid" | ... 46 more ... | "$isSingleNested">>, Exclude<...> | ... 2 more ... | Exclude<...>>' is not assignable to type 'T'.
  'T' could be instantiated with an arbitrary type which could be unrelated to 'Pick<Pick<_LeanDocument<T & Document<any>>, "_id" | "__v" | "id" | Exclude<keyof T, "$ignore" | "$isDefault" | "$isDeleted" | "$isEmpty" | "$isValid" | ... 46 more ... | "$isSingleNested">>, Exclude<...> | ... 2 more ... | Exclude<...>>'.ts(2322)

My tsconfig.json is as follows

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "es2017",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true
  }
}
@vkarpov15 vkarpov15 added this to the 5.11.18 milestone Feb 18, 2021
@vkarpov15 vkarpov15 added the typescript Types or Types-test related issue / Pull Request label Feb 18, 2021
@vkarpov15
Copy link
Collaborator

This is because @types/mongoose returned any from toObject(), which is not necessarily correct. In v5.11.x we make toObject() infer the type the returned object should have based on the schema, but that seems to cause problems for the design pattern you mentioned, even though T should be equivalent to LeanDocument<T & Document> in the above example.

We'll add a generic parameter to toObject() to allow you to overwrite the returned type, like this: return document.toObject<T>();

vkarpov15 added a commit that referenced this issue Feb 22, 2021
This was referenced Mar 5, 2021
This was referenced Mar 12, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
typescript Types or Types-test related issue / Pull Request
Projects
None yet
Development

No branches or pull requests

2 participants