How To Solve “Property Does Not Exist On Type Object” In Typescript

Property does not exist on type Object in TypeScript

Today’s topic, I will show you how to solve the ‘property does not exist on type object‘ error in Typescript. But before that, let’s find out what causes it. Stay tuned to better understand the solutions.

Why does the “Property does not exist on type Object” error in TypeScript happen?

This error happens when you work with TypeScript, a frontend application has accessed the global window object. This might occur when you are adding something to this global object. 

Example: 

let student: object;
student = {
  name:  "Johnny Kaiz",
  id: 123,
  age: 18
};

console.log(student.tuitionfee);

Output: 

error TS2339: Property 'tuitionfee' does not exist on type 'object'

When you try to access a property like: console.log(student.tuitionfee) the program will crash because the property ‘tuitionfee‘ is does not exist in ‘student’ object.

How to fix this error?

Adding property to the type we set to the variable

If you already know the property’s name and value, just add it variable. To specify the object’s properties, you should declare the following syntax.

Example:

let student: object;
student = {
  name: string,
  id: number,
  age: number,
  tuitionfee: number
};

Then you assign data type to each variable in ‘student’ object :

student = {
  name: "Johnny Kaiz",
  id: 123,
  age: 18,
  tuitionfee: 10000
};

Output:

{
  "name": "Johnny Kaiz",
  "id": 123,
  "age": 18,
  "tuitionfee": 10000
}

Using Object.assign() feature

You don’t want to worry about types and don’t use TypeScript. 

You can use  Object.assign() feature. 

Object.assign() is used to copy the values ​​of all properties of one or more source objects to a target object.

Syntax:

Object.assign(target, sources)

Parameters:

  • target: Target object
  • sources: Source objects 

Example:

const sourceObj = {tuitionfee : 10000};

let student: object;
student = {
  name: "Johnny Kaiz",
  id: 123,
  age: 18
};

const newStudent = Object.assign(student, sourceObj);
console.log(newStudent); 

Output :

 { 
    name: 'Johnny Kaiz',
    id: 123,
    age: 18,
    tuitionfee: 10000
 }

Using KEYABLE 

This method is ​​used when you don’t know the object’s name or data.

Syntax:

 {[key: string]: any}

The value of this syntax returns is ‘any’ type.

Example:

let student: object;
student = {
  {[key: string]: string};
  name: string;
};

Summary 

The above methods solve the “Property does not exist on type Object” error in Typescript. If you have any questions or helpful solutions, just feel free to leave them in the comment below, and don’t forget to wait for our new articles in LearnShareIt. 

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *