Blog Logo
TAGS

When to use never and unknown in TypeScript - LogRocket Blog

The never and unknown primitive types were introduced in TypeScript v2.0 and v3.0, respectively. TypeScript is carefully designed according to principles of type theory, but it is also a practical language, and its features all have practical uses – including never and unknown. To understand those uses, we will be doing a deep dive into TypeScript types. We’ll cover: What are TypeScript types? The TypeScript never type Type inference and type annotations What are type assertions? What are type guards? Using never with conditional types When to use the unknown type in TypeScript What is type narrowing with unknown? TypeScript: any vs. unknown vs. never What are TypeScript types? When you get down to a fundamental definition, a type is a set of possible values, and nothing more. For example, the type string in TypeScript is the set of all possible strings. The type Date is the set of all instances of the Date class (plus all structurally-compatible objects), and the type Iterable<T> is the set of all objects that implement the iterable interface for the given type of iterated values. TypeScript is especially faithful to the set-theoretic basis for types; among other features, TypeScript has union and intersection types. A type like string | number is called a “union” type because it literally is the union of the set of all strings, and the set of all numbers: The set string | number contains both the string and number sets. Because string | number contains all string and all number values, it is said to be a supertype of string and of number: unknown is the set of all possible values. Any value can be assigned to a variable of type unknown. This means that unknown is a supertype of every other type. For that reason, unknown is called the top type: The set unknown contains all other sets. never is the empty set. There is no value that can be assigned to variable of type never. In fact, it is an error for the type of value to resolve to never because that would be a contradiction. The empty set can fit inside any other set, so never is a subtype of every other type. That is why never is called the bottom type:¹ The empty set, never, exists as a point inside every other set. The bottom and top types have the useful properties of being the identity element with respect to the union and intersection operations respectively. For any type T: T | never ⇒ T T & unknown ⇒ T This is analogous to the idea that adding zero to a number does not change it, and the same goes for multiplying a number by one. Zero is the identity element for addition, and one is the identity element for multiplication. A union with the empty set does not add anything, so never is the identity with respect to unions. An intersection selects