Property does not exist on type in TypeScript

When you get ‘Property does not exist’ error in TypeScript you should understand how to fix this problem. We determinate 3 of the most common ways to solve it. But first of all, let’s make it clear: It is quite easy to assign properties to JavaScript objects.

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

After that we get these values for obj:

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

TypeScript problem for ‘object’ types

Running this code in TypeScript gives us this error for type ‘object’.

let obj = {}
obj.key1 = 1;
Property 'key1' does not exist on type 'object'.

So, how should we work with JSON objects in TypeScript? Here are the best 3 solutions to fix ‘Property does not exist’ issue for different types like ‘object’ or ‘angular’.

The Quick Fix of ‘Property does not exist’

In TypeScript, we can use a function to specify the parameter types and return types.

Simply saying, we just need to print our objects, so that TypeScript understands what is and isn’t allowed for the keys and values.

A quick and dirty way of doing this is to assign the object to type any. This type is mostly used for dynamic content of which we may not know the specific type or so. Essentially, we are opting out of type checking that variable.

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

But here is another question related: What’s the point of casting everything to type any just to use it? What is the purpose of using TypeScript then? And here we use “Proper fix” option.

The Proper Fix

Consistency is key. To stay consistent with the TypeScript standard, we are able to define an interface that allows the keys of type string and values of type any.

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

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

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

The JavaScript Fix

Pure JavaScript. What if we don’t want to worry about types? Answer is pretty simple – Don’t use TypeScript then.

Or you can use Object.assign() feature.

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

Conclusion on ‘Property does not exist’

All the ways described before are working and you can choose the one you like most of all. Feel free to ask us any questions if you have. And you also may be interested in load to GCash or any other articles of Technologeek.