惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Recent Commits to openclaw:main
Recent Commits to openclaw:main
L
LangChain Blog
月光博客
月光博客
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 【当耐特】
宝玉的分享
宝玉的分享
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Last Week in AI
Last Week in AI
人人都是产品经理
人人都是产品经理
博客园_首页
T
Tailwind CSS Blog
P
Proofpoint News Feed
雷峰网
雷峰网
D
Darknet – Hacking Tools, Hacker News & Cyber Security
IT之家
IT之家
V
Vulnerabilities – Threatpost
阮一峰的网络日志
阮一峰的网络日志
C
CERT Recently Published Vulnerability Notes
Attack and Defense Labs
Attack and Defense Labs
S
Schneier on Security
Security Archives - TechRepublic
Security Archives - TechRepublic
L
Lohrmann on Cybersecurity
V
Visual Studio Blog
云风的 BLOG
云风的 BLOG
WordPress大学
WordPress大学
The Register - Security
The Register - Security
N
Netflix TechBlog - Medium
Hugging Face - Blog
Hugging Face - Blog
Project Zero
Project Zero
博客园 - 叶小钗
F
Full Disclosure
大猫的无限游戏
大猫的无限游戏
Latest news
Latest news
S
SegmentFault 最新的问题
C
Cyber Attacks, Cyber Crime and Cyber Security
Google Online Security Blog
Google Online Security Blog
Recorded Future
Recorded Future
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Hacker News - Newest:
Hacker News - Newest: "LLM"
腾讯CDC
L
LINUX DO - 最新话题
Google DeepMind News
Google DeepMind News
P
Privacy International News Feed
I
InfoQ
F
Fortinet All Blogs
Vercel News
Vercel News
H
Hackread – Cybersecurity News, Data Breaches, AI and More
T
Threatpost
T
Tenable Blog
B
Blog RSS Feed

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
unknown vs any in TypeScript
Dmitri Pavlutin · 2021-09-08 · via Dmitri Pavlutin Blog

A variable of type any can be assigned with anything:


let myVar: any = 0;

myVar = '1';

myVar = false;


Many TypeScript guides discourage the use of any because using it throws away the type restrictions — the first reason why you use TypeScript!

TypeScript (version 3.0 and above) also provides a special type unknown that is similar to any. You can assign any value to an unknown type variable as well:


let myVar: unknown = 0;

myVar = '1';

myVar = false;


Now... the big question is: what is the difference between using any and unknown?

Let's find out in this post.

1. unknown vs any

To better understand the difference between unknown and any, let's start with writing a function that wants to invoke its only argument.

Let's make the only parameter of invokeAnything() as any type:


function invokeAnything(callback: any) {

callback();

}

invokeAnything(1);


Because callback param is of any type, the statement callback() won't trigger type errors. You can do anything with a variable of type any.

But running the script throws a runtime error: TypeError: callback is not a function. 1 is a number and cannot be invoked as a function — and TypeScript hasn't protected you from this error!

How to allow invokeAnything() function to accept any kind of argument, but force a type check on that argument, for example, if invoking it as a function?

Welcome unknown!

An unknown type variable, same as any, accepts any value. But when trying to use the unknown variable, TypeScript enforces a type check. Exactly what you need!

Let's change the type of callback param from any to unknown, and see what happens:


function invokeAnything(callback: unknown) {

callback(); // Type error: 'callback' is of type 'unknown'

}

invokeAnything(1);


Because the callback argument is of type unknown, the statement callback() has a type error Object is of type 'unknown'. Now, contrary to any, TypeScript protects you from invoking something that might not be a function!

You need to perform type checking before using a variable of type unknown. In the example, you would simply need to check if callback is a function type:


function invokeAnything(callback: unknown) {

if (typeof callback === 'function') {

callback();

}

}

invokeAnything(1);


Having added typeof callback === 'function' check, you can safely invoke callback() because unknown has narrowed to Function type. No type errors and no runtime errors! Great!

2. The mental model of unknown vs any

To be honest, I had difficulties understanding unknown when I had been learning it. How does it differ from any, since both types accept any value?

Here's the rule that had helped me understand the difference:

  • You can assign anything to unknown type but you have to do a type check or type assertion to operate on unknown
  • You can assign anything to any type and you can perform any operation on any

The example above has demonstrated exactly the similarity and difference between unknown and any.

The case of unknown:


function invokeAnything(callback: unknown) {

if (typeof callback === 'function') {

callback();

}

}

invokeAnything(1);


The type check here is typeof callback === 'function' — checking whether the callback is a function. The type of callback narrows to function type.

The case of any:


function invokeAnything(callback: any) {

callback();

}

invokeAnything(1);


callback being any, TypeScript doesn't enforce any type checking for the statement callback().

3. Conclusion

unknown and any are 2 special types that can hold any value.

unknown is recommended over any because it provides safer typing — you have to use type assertion or narrow to a specific type if you want to perform operations on unknown.

Challenge: can you write a utility type IsUnknown<T> which evaluates to true if T is unknown and false otherwise?