Let's talk in detail about the difference between unknown and any in TypeScript

Let's talk in detail about the difference between unknown and any in TypeScript

Preface

We know that a variable of type any can be assigned any value.

let myVar: any = 0;
myVar = '1';
myVar = false;

The TypeScript guidelines discourage the use of any because using it will lose type constraints - and the need for type constraints is one of the reasons we chose TypeScript, so it's a bit contrary.

TypeScript (version 3.0 and above) also provides a special type called unknown that is similar to any. We can also assign any value to a variable of type unknown:

let myVar: unknown = 0;
myVar = '1';
myVar = false;

Now there is a question, what is the difference between any and unknown?

1. unknown vs any

To better understand the difference between unknown and any, let's start by writing a function that we want to call on its only argument.

We set the only parameter of invokeAnything() to be of type any.

function invokeAnything(callback: any) {
  callback();
}

invokeAnything(1); // throws "TypeError: callback is not a function"

Because the callback parameter can be of any type, the statement callback() will not trigger a TypeError. We can do anything with a variable of type any.

But running it throws a runtime error: TypeError: callback is not a function. 1 is a number and cannot be called as a function. TypeScript does not protect the code from this error.

So how can we allow the invokeAnything() function to accept any type of parameter, while forcing type checking on the parameter to prevent the above error?

Please invite unknown brother to take control of the situation.

Like any, the unknown variable accepts any value. But TypeScript enforces type checking when you try to use an unknown variable. Isn't this what we want?

function invokeAnything(callback: unknown) {
  callback();
  // Object is of type 'unknown'
}

invokeAnything(1);

Because the callback parameter is of type unknown, the statement callback() has a type error: Object is of type 'unknown'. As opposed to any, TypeScript will protect us from calling something that might not be a function.

Before using a variable of unknown type, you need to perform type checking. In this case, we just need to check if callback is a function type.

function invokeAnything(callback: unknown) {
  if (typeof callback === 'function') {
    callback();
  }
}

invokeAnything(1);

2. The mental model of unknown and any

To be honest, when I was studying, I had a hard time understanding unknown. How is it different from any, since both types accept any value? Here are the rules that helped me understand the difference between the two:

  • You can assign anything to an unknown type, but you cannot operate on unknown before performing a type check or type assertion.
  • You can assign anything to any type, and you can perform any operation on any type.

The above example illustrates the similarities and differences between unknown and any.

unknown Example:

function invokeAnything(callback: unknown) {
  // You can assign anything to the `unknown` type,
  // But you can't operate on `unknown` before doing a type check or type assertion if (typeof callback === 'function') {
    callback();
  }
}

invokeAnything(1); // You can assign anything to `unknown` type

The type check typeof callback === 'function' checks whether callback is a function. If so, it can be called.

any Example:

function invokeAnything(callback: any) {
  // You can perform any operation on `any` type callback();
}

invokeAnything(1); // You can assign anything to the `any` type

If callback is any, TypeScript will not enforce any type checking on the callback() statement.

3. Summary

Unknown and any are two special types that can hold any value.

It is recommended to use unknown instead of any because it provides more type safety - if you want to operate on unknown, you must use a type assertion or narrow it to a specific type.

~~ End. I’m Xiaozhi. My girlfriend works in the education and training industry. The salary she’s been getting lately is a bit low, so I plan to work more and earn more money.

There is no way to know in real time what bugs may exist in editing. In order to solve these bugs afterwards, a lot of time was spent on log debugging. By the way, I would like to recommend a useful BUG monitoring tool Fundebug.

Original text: dmitripvlutin.com/typescript-…

Summarize

This is the end of this article about the difference between unknown and any in TypeScript. For more information about the difference between unknown and any in TypeScript, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

<<:  MySQL lock control concurrency method

>>:  Button is stretched on both sides in IE

Recommend

Detailed explanation of the solution to permission denied in Linux

Permission denied: The reason for this is: there ...

Install docker offline by downloading rpm and related dependencies using yum

You can use yum to install all dependencies toget...

PostgreSQL materialized view process analysis

This article mainly introduces the process analys...

MySQL 8.0.17 installation graphic tutorial

This article shares with you the MySQL 8.0.17 ins...

Introduction to document.activeELement focus element in JavaScript

Table of contents 1. The default focus is on the ...

MySQL chooses the right storage engine

When it comes to databases, one of the most frequ...

Advertising skills in the Baidu Union environment (graphic tutorial)

Recently, students from the User Experience Team o...

JavaScript BOM location object + navigator object + history object

Table of contents 1. Location Object 1. URL 2. Pr...

MySQL implements a solution similar to Oracle sequence

MySQL implements Oracle-like sequences Oracle gen...

Implementation of mysql configuration SSL certificate login

Table of contents Preface 1. MySQL enables SSL co...