unknown is a new type that has been added in TypeScript 3. Before TypeScript 3, we may have used the any type when we weren't sure of all the properties and methods in an object from a third-party library. However, when we declare a variable with the any type, the TypeScript compiler won't do any type checking on it. The unknown type can be used in these situations to make our code more type-safe. This is because unknown types are type-checked. So, unknown can often be used as an alternative to any.
In the TypeScript playground, let's go through an example of a function using any and an improved version using unknown:
- First, let's create a logScores function that takes in a parameter of type any. It logs out the name and scores properties from the argument to the console:
function logScores(scores: any) {
console.log(scores.firstName);
...