javascripttypescripttypesundefinedtypeguards

Typescript check if property in object in typesafe way


The code

const obj = {};
if ('a' in obj) console.log(42);

Is not typescript (no error). I see why that could be. Additionally, in TS 2.8.1 "in" serves as type guard.

But nevertheless, is there an way to check if property exists, but error out if the property is not defined in the interface of obj?

interface Obj{
   a: any;
}

I'm not talking about checking for undefined...


Solution

  • You don't get an error because you use a string to check if the property exists.

    You will get the error this way:

    interface Obj{
       a: any;
    }
    
    const obj: Obj = { a: "test" };
    
    if (obj.b)          // this is not allowed
    if ("b" in obj)     // no error because you use string
    

    If you want type checking to work for string properties you could add index signatures using this example