sylvainpolletvillard / ObjectModel

Strong Dynamically Typed Object Modeling for JavaScript
http://objectmodel.js.org
MIT License
467 stars 30 forks source link

Typescript expected number of arguments when using defaultTo() #164

Open gbcreation opened 1 year ago

gbcreation commented 1 year ago

Hello,

Given this code sample:

import { Model } from "objectmodel"

const classSchema = {
    id: String,
    lastName: [String],
    firstName: [String]
}

const defaultValues = { lastName: "a" }

class Character extends Model(classSchema).defaultTo(defaultValues) {}

const o = new Character({ id: "1" }) // <- typescript: Expected 0 arguments, but got 1.
console.log(o)

TypeScript underlines { id: "1" } with the error "Expected 0 arguments, but got 1" when creating a new instance of the Character class.

Is there something wrong in this code?

Note that I get the same TypeScript error with the ObjectModel example given at chapter Default values assignment in the doc.

sylvainpolletvillard commented 1 year ago

Nothing wrong with your code. TypeScript definitions have been recently added to the project and they are hard to code and unit test. Thanks for the bug report

sylvainpolletvillard commented 1 year ago

I improved the type definitions with defaultTo() in v4.4.4, released just now. Can you update and confirm that it fiixed your issue ? Thanks

gbcreation commented 1 year ago

Thank you very much for your quick answer.

v4.4.4 fixes the typescript error for the ObjectModel example in the Default values assignment chapter.

It also fixes it for the code sample in my first post, however I now get another error:

class Character extends Model(classSchema).defaultTo(defaultValues) {}
                     // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                     //    |_ typescript: Base constructors must all have the same return type
sylvainpolletvillard commented 1 year ago

Sounds like a limitation of TypeScript, based on my understanding of this issue: https://github.com/microsoft/TypeScript/issues/40110

I can remove the type error but will lose the ability to return the default value as type when no arguments are passed.