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.

devFlipCards 2024

Do you accept cookies?

Cookies are small amounts of data saved locally on you device, which helps our website - it saves your settings like theme or language. It helps in adjusting ads and in traffic analysis. By using this site, you consent cookies usage.