6. What's the difference between `any` and `unknown`?

The type any is what's known as a wildcard - it allows replacing any other type. Its property is that it can be assumed to represent any other type. You can refer to any field or function of an object marked as any, and the compiler won't return an error.

On the other hand, the unknown type is the opposite of any - a variable of this type cannot be treated as any specific type, and it's not possible to access any properties of an object unless it's explicitly casted to a more specific type.

type ObjType = { field: { nestedField: string } } const obj: ObjType = {field: {nestedField: "nestedValue"}}; console.info(obj.field.nestedField) // nestedValue console.info((obj as any).notExistingField) // undefined, no Error thrown console.info((obj as any).field.nestedField) // nestedValue console.info((obj as unknown).notExistingField) // Compilation error - Object is of type 'unknown'. console.info((obj as unknown).field.nestedField) // Compilation error - Object is of type 'unknown'.
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.