How to Fix "Property does not exist on type {}" Error in TypeScript


Assigning properties to JavaScript objects is quite simple.

let obj = {}
obj.key1 = 1;
obj['key2'] = 'dog';

This would add or update these values for obj:

obj: {
  key1: 1, 
  key2: 'dog'
}

The issue with TypeScript

We can try running the same code in TypeScript:

let obj = {}
obj.key1 = 1;

But it would yield this error below.

Property `key1` does not exist on type '{}'.

If obj is typed as an Object, we’ll get a similar error.

Property `key1` does not exist on type Object

There are multiple ways we can solve these type check errors.

In TypeScript, we can type a function by specifying the parameter types and return types.

Similarly, we need to type our objects, so that TypeScript knows what is and isn’t allowed for our keys and values.

1. Using an interface

In order to stay consistent with the TypeScript standard, we can define an interface that allows keys of type string and values of type any.

interface ExampleObject {
  [key: string]: any
}
let obj: ExampleObject = {};
obj.key1 = 1;
obj['key2'] = 'dog';

What if this interface is only used once? We can make our code a little more concise with the following:

let obj: {[k: string]: any} = {};
obj.key1 = 1;
obj['key2'] = 'dog';

2. Using the any type

A quick and dirty way of “typing” our objects is to assign the object to type any. This type is generally used for dynamic content of which we may not know the specific type.

In other words, we are opting out of type checking that variable.

let obj: any = {}
obj.key1 = 1;
obj['key2'] = 'dog';

In cases where the schema should and is defined, an interface is generally recommended. Unfortunately, defaulting objects to type any defeats the purpose of TypeScript.

3. Using Object.assign()

What if we don’t want to worry about types? Well, don’t use TypeScript 😉

A pure JavaScript solution might be to use Object.assign().

let obj = {};
Object.assign(obj, {key1: 1});
Object.assign(obj, {key2: 'dog'});

That being said, if we’re opting to use TypeScript, more often than not, it’ll be ideal to create interfaces for our objects.