Home > Software design >  Type checking JavaScript for object properties which change type
Type checking JavaScript for object properties which change type

Time:03-19

With this https://code.visualstudio.com/docs/nodejs/working-with-javascript#_type-checking-javascript enabled in Settings, there are some objects with valid type changes.

Examples:

let options = {
        logging: false,
    }    
if (process.env.DEBUG_LOG == "true") {
        options.logging = console.log // vscode error: is not assignable to boolean
    }    

or

 let pgconfig = {
        ssl: { rejectUnauthorized: false },
        max: 5,
    }
if (process.env.NODE_ENV == 'development') {
        //no SSL on localhost
        pgconfig.ssl = false // vscode error
    }

These type changes are valid for the functions using them.

How to make vscode understand that both work, without using

// @ts-ignore comment on the line before the error:

This is a .js file, not .ts. I tried

let options = {
        logging: <any> false,
    } 

or
let options = {
        logging: false as any,
    } 

but these don't work in JS.

More info: https://www.typescriptlang.org/docs/handbook/type-checking-javascript-files.html (not saying how to handle type changes)

CodePudding user response:

Since option literals are open-ended, you can trick the compiler into deriving an any type for a field by assigning to the field after object construction:

let options = {};
options.logging = false;

An alternative is to use JSDoc to add an @type tag, which lets you be a bit more strict than the any type:

/** @type {{logging: (boolean|function(...*))}} */
let options = {
    logging: false,
}

(I hope I got that syntax right, but I didn't test it. See also Types in the Closure Type System.)

  • Related