Ignore 'Property does not exist on type' TypeScript Error

avatar

Borislav Hadzhiev

Wed Mar 16 20222 min read

Ignore 'Property does not exist on type' TypeScript Error #

Use a type assertion to ignore the 'Property does not exist on type' error in TypeScript, e.g. (obj as any).myProperty. Casting the object to any disables type checking and allows us to access any property on the object without getting any errors.

index.ts
const obj = { name: 'James', country: 'Germany', } as unknown as { a: number }; const result1 = (obj as any).name; // 👈️ type as any console.log(result1); // 👉️ "James"

We used a type assertion to type the obj variable as any.

Type assertions are often used when fetching data from a remote source like a database, because TypeScript likely doesn't know the type of the data you fetch with an API request.

Type assertions are used when we have information about the type of a value that TypeScript can't know about.

When using them, we effectively tell TypeScript that value X will be of type Y and not to worry about it. This could cause runtime errors if we are wrong.

Unfortunately, you would always have to use a type assertion when accessing properties that don't exist on the object's type.

An alternative approach is to use the // @ts-ignore comment to disable type checking for the next line.

index.ts
const obj = { name: 'James', country: 'Germany', } as unknown as { a: number }; // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore const result2 = obj.country; console.log(result2); // 👉️ "Germany"

The // @ts-ignore comment disables all type checking for the next line.

If you use a linter, it might have a rule that prevents you from using ts comments. You can disable it for a line like in the example above, disable the rule for the entire file, or disable it globally in your .eslintrc file.

If you need to disable the rule for the entire file, use the following syntax:

index.ts
/* eslint-disable @typescript-eslint/ban-ts-comment */

If you're looking to avoid having to cast the variable as any every time you need to access a property, you can cast the variable as any when declaring it, if you have access to where it was declared.

index.ts
const obj = { name: 'James', country: 'Germany', } as any; // 👉️ Can now access any property without getting errors console.log(obj.name); // 👉️ "James" console.log(obj.doesNotExist); // 👉️ undefined

If we set the object's type as any when declaring it, we can access any property on it without getting errors.

Note that it's always better to look for a way to type the object correctly and look for a type safe solution. If that isn't possible, a type assertion with any gets the job done.

Use the search field on my Home Page to filter through my more than 1,000 articles.