Borislav Hadzhiev
Wed Mar 16 2022·2 min read
Photo by Angelina Litvin
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.
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.
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.
An alternative approach is to use the // @ts-ignore
comment to disable type
checking for the next line.
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:
/* 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.
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.