Hi, I'm Jacob. Enjoying devFlipCards? Buy me a coffee

5. Is it worth to use `any`?

The any type is a so-called wildcard - it allows substituting any other type. Its characteristic feature is that it can be assumed to represent any other type. You can reference any field or function of an object marked as any, and the compiler won't raise an error.

The issue is that it loses typing, which is the most significant advantage of TypeScript over JavaScript. It means there's no checking of variable types, which can lead to hard-to-detect errors occurring only in runtime.

const randomObject = {anotherField: "value"}; console.info(randomObject.anotherField) // value console.info((randomObject as any).another.field) // TypeError: Cannot read properties of undefined (reading 'field')

The compiler didn't report an error when accessing the another field in the randomObject object because any allows assuming that the object has any properties. The TypeError is thrown only in runtime.

In summary - it's not advisable to use any in TypeScript code, and in the vast majority of cases, its usage isn't necessary.

Struggling to find common date to meet with your friends? Try our new tool
commondate.xyz