Home > Mobile >  type | undefined not assignable to type regardless of null check
type | undefined not assignable to type regardless of null check

Time:11-18

In my following code i get a Argument of type 'Definition | undefined' is not assignable to parameter of type 'Definition'. error. But as you see i check the object value with if (defs[type] != undefined). But at this.addDefinition(type, defs[type]); the error is thrown anyway.

    public static addDefinitions(defs: Record<string, Definition>): void {
        Object.keys(defs).forEach((type: string): void => {
            if (defs[type] != undefined) {
                this.addDefinition(type, defs[type]);
            }
        });
    }

can it probably a wrong setting in my tsconfig?

CodePudding user response:

I wish I could give a more thorough answer, but here's the solution TS may be expecting on a plain Record<string,T> object. (Take with a grain of salt: My guesstimate is that TS does not record type as a specific string, and even within the same flow it will "forget" it checked that key.)

    public static addDefinitions(defs: Record<string, Definition>): void {
        Object.keys(defs).forEach((type: string): void => {
            const def = defs[type] // fix the value to a variable

            if (def) {
                this.addDefinition(type, def); // def is defined
            }
        });
    }
  • Related