How To Ignore ‘Property does not exist on type’ In TypeScript

Ignore ‘Property does not exist on type’

The error “Property does not exist on type” is beneficial when you make the mistake of adding some invalid property to a type. But for some reason, if you want to ignore it. I will show you how to ignore ‘property does not exist on type’ error. Let’s go into detail.

The solutions to ignore ‘Property does not exist on type’

The cause of this error

The error “Property does not exist on type” happens when you try to point to a property that does not exist in a type.

Example:

type Person = {
	name: string,
	age: number,
	id: string[],
	greet: string
}
  
const james: Person = {
	name: "James",
	age: 23,
	id: ["12", "42", "402"],
	greet: "Hello From Learn Share IT."
};
  
james.address;

Here I try to point to address property that doesn’t exist in the james object so that I will get an error.

Error:

Property 'address' does not exist on type 'Person'.

Sometimes this error will be beneficial, like in this situation. You won’t have to worry about you will make mistakes and pointing to some wrong properties, and making your logic go wrong. But sometimes, you will want to ignore this error. Here is solutions.

Set ‘any’ type

With any type, you can ignore the error “Property does not exist on type”. You can explicitly set any type by creating an object with a set type like this:

const james: any = {
    name: "James",
    age: 23,
    id: ["12", "42", "402"],
    greet: "Hello From Learn Share IT."
};
  
const ignored = james.address;
console.log(ignored);

Output: 

undefined

Here I will get no error with any type.

Use ‘as’ keyword

You can also explicitly set type with the as keyword. 

Example:

const james = {
    name: "James",
    age: 23,
    id: ["12", "42", "402"],
    greet: "Hello From Learn Share IT"
};
  
const ignored = (james as any).address;
console.log(ignored);  

Output:

undefined

If you want to make things right, you can create a new type, extend it from the old type and add any property that you want.

Example:

type Person = {
    name: string,
    age: number,
    id: string[],
    greet: string
}
  
interface infor extends Person {
    address: string;
}
  
const james: infor = {
    name: "James",
    age: 23,
    id: ["12", "42", "402"],
    greet: "Hello From Learn Share IT",
    address: "England",
};
  
console.log(james);

Output:

{ 
  "name": "James",
  "age": 23, 
  "id": [ "12", "42", "402" ], 
  "greet": "Hello From Learn Share IT",
  "address": "England" 
}

Summary

In this tutorial, I’ve showed you how to ignore ‘Property does not exist on type’ error in TypeScript. You can set your object to any type or create your own type and add a new property. If you have any problems, please comment below, and I will respond as possible. Thank you for reading!

Maybe you are interested:

Leave a Reply

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