sylvainpolletvillard / ObjectModel

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

Use in Typescript ? #168

Closed gordielachance closed 1 year ago

gordielachance commented 1 year ago

Can objectmodel work with TypeScript ?

This simple example returns an error :

    function isTrimmedString(str: string): boolean {
      return str.trim() === str;
    }

    export const TrimmedString = BasicModel(String).assert(isTrimmedString).as("TrimmedString");

Unable to compile TypeScript: error TS2345: Argument of type '(str: string) => boolean' is not assignable to parameter of type 'Assertion'. Types of parameters 'str' and 'variable' are incompatible. Type 'unknown' is not assignable to type 'string'.

export const UriString = TrimmedString.extend().assert(isUriString);

sylvainpolletvillard commented 1 year ago

Yes, ObjectModel can work with TypeScript, but the TS definitions have been recently added to the project and some improvements can still be added. Here, the assertion function arguments are not yet narrowed based on the type of the model.

Current workaround is to not assume the type of the variable in assertions:

function isTrimmedString(str: unknown): boolean {
 return typeof str === "string" && str.trim() === str;
}
sylvainpolletvillard commented 1 year ago

closed after inactivity