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

Analysis and solution of the problem that MySQL instance cannot be started

Table of contents Preface Scenario Analysis Summa...

Tutorial on installing Microsoft TrueType fonts on Ubuntu-based distributions

If you open some Microsoft documents with LibreOf...

Implementation method of Mysql tree recursive query

Preface For tree-structured data in the database,...

Example code of html formatting json

Without further ado, I will post the code for you...

How to build and deploy Node project with Docker

Table of contents What is Docker Client-side Dock...

In-depth analysis of MySQL index data structure

Table of contents Overview Index data structure B...

A detailed introduction to for/of, for/in in JavaScript

Table of contents In JavaScript , there are sever...

How to use Axios asynchronous request API in Vue

Table of contents Setting up a basic HTTP request...

Detailed configuration of mysql8.x docker remote access

Table of contents Environmental conditions Errors...

Docker uses dockerfile to start node.js application

Writing a Dockerfile Taking the directory automat...

How to use limit_req_zone in Nginx to limit the access to the same IP

Nginx can use the limit_req_zone directive of the...

Creating Responsive Emails with Vue.js and MJML

MJML is a modern email tool that enables develope...

Tutorial on installing mysql5.7.18 on mac os10.12

I searched the entire web and found all kinds of ...