Typescript check if property in object in typesafe way

cdbeelala89

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...

Kokodoko

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Typescript: what is a typesafe way to detect if an optional property exists

TypeScript: remapping object properties in typesafe

Typescript: Check if object has property and check property value

How to check object property empty value in typescript

typescript check dynamically if string is a property of complex object

Check if a property exists on global or window object in TypeScript

Safe way to check if a property of an object contains a substring

What is the correct way to add a property to an Object [Typescript]

Simpler way to check literal object type in TypeScript

Is there any way to check if an object is a type of enum in TypeScript?

TypeScript: Is it possible to map tuples in a typesafe way?

How to check if object has property and property value is true in TypeScript

How to have typescript check for valid object property names

TypeScript - check if object's property is a function with given signature

Is there any safe way to check the deep of object's property?

Create TypeSafe Object literal based upon existing object in TypeScript

Typescript check if property exist

What is the best way to check which object is returned from an API in typescript?

TypeScript: Is there a cleaner way to null check a hierarchical object structure?

(TypeScript 5.0.2) Is possible to infer a typesafe to a json object after transform it keys?

Check is object exists in property

Check object for property

Typescript object with a known property

Typescript is Type for object property

Typescript object property typings

Typescript - Conditional property of object

Omit an object property in typescript

Access Object property in Typescript

Check if the value of an object property is an object