An
It can be significantly helpful when moving from a JavaScript to a TypeScript project. During the transition, it might help you understand code better and stay safer.
Before we try to understand the difference between the
We can assign whatever we want to variables with
let anyValue: any = "any value";
anyValue = true;
anyValue = 123;
console.log(anyValue);
let unknownValue: unknown;
unknownValue = "unknown value";
unknownValue = true;
unknownValue = 123;
console.log(unknownValue);
But this is where the similarities end up.
Unlike
Consider the following example:
const anyValue: any = "any value";
console.log(anyValue.add());
or even this:
const anyValue: any = true;
anyValue.typescript.will.not.complain.about.this.method();
In this case, we won’t get a build time error. Instead, we will get a runtime error, which is worse.
To put it simply in other words — when we use type
With an
Let’s take a look at it in action:
let unknownValue: unknown;
unknownValue = "unknown value";
unknownValue.toString(); // Error: Object is of type 'unknown'.
unknownValue = 100;
const value = unknownValue + 10; // Error: Object is of type 'unknown'.
unknownValue = console;
unknownValue.log("test"); // Error: Object is of type 'unknown'.
Every time we try to do something with this, we get an error.
In order to work with the
Using type assertion:
let unknownValue: unknown;
unknownValue = function () {};
(unknownValue as Function).call(null);
Using type guard:
let unknownValue: unknown;
unknownValue = "unknown value";
if (typeof unknownValue === "string") unknownValue.toString();
Using self-defined type guard:
let unknownValue: unknown;
type User = { username: string };
function isUser(maybeUser: any): maybeUser is User {
return "username" in maybeUser;
}
unknownValue = { username: "John" };
if (isUser(unknownValue))
console.log(unknownValue.username);
Using assertion function:
let unknownValue: unknown;
unknownValue = 123;
function isNumber(value: unknown): asserts value is number {
if (typeof value !== "number") throw Error("Not a number");
}
isNumber(unknownValue);
unknownValue.toFixed();