unknown is a safer alternative to any.
TypeScript will restrict the use of unknown types, as demonstrated in the example below:
let w: unknown = 1; w = “string”; // no error w = { runANonExistentMethod: () => { console.log(“I think therefore I am”); } } as { runANonExistentMethod: () => void} // How can we avoid the error for the code commented out below when we don’t know the type? // w.runANonExistentMethod(); // Error: Object is of type ‘unknown’. if(typeof w === ‘object’ && w !== null) { (w as { runANonExistentMethod: Function }).runANonExistentMethod(); } // Although we have to cast multiple times we can do a check in the if to secure our type and have a safer casting |
unknown is most effective when the type of data is not initially known. To specify a type later, you’ll need to perform a type cast. Casting involves using the as keyword to indicate that a property or variable should be treated as a specific type. |