Recently, during an interview, I was asked about TypeScript knowledge, and one of the questions was: When should we use never
and unknown
in TypeScript?
I felt I didn't answer well, so I revisited the relevant knowledge to share. This article is not a general introduction to TypeScript types, so don't rush; just take it step by step.
A Brief Discussion on TypeScript Types
First, we need to understand what TypeScript types are.
Simply put, the string
type is the type set of string variables in TypeScript. Similarly, number
is the type set of numeric variables. When we write the following code:
const stringOrNumber: string | number = '1';
The union type string | number
is born, which is the union of the string type set and the number type set.
In TypeScript, we can assign variables of string type or number type to stringOrNumber
. Besides these, what other types of variables can we assign to stringOrNumber
?
The answer is:
never
any
π We don't talk about the
any
type, at least not before resigning, and we don't use theany
type in projects.
The never
type is an empty set, located at the innermost layer of the type system.
When we define a variable's type as unknown
, we actually need a value of an unknown type. For example:
let foo: unknown;
foo = stringOrNumber; // ok
function demo(param: unknown) {
// ...
if(typeof param === 'string') {
// ...
}
}
demo(stringOrNumber); // ok
unknown
is the superset of all type sets, while never
is the subset of all types (bottom type).
A Brief Analysis of the never
Type
Let's look at some code before discussing further:
function asyncTimeout(ms: number): Promise<never> {
return new Promise((_, reject) => {
setTimeout(() => reject(new Error(`Async Timeout: ${ms}`)), ms)
})
}
The above code is an asynchronous timeout function, with a return type of Promise<never>
. Let's continue to implement a request function that supports timeout:
function fetchData(): Promise<{ price: number }> {
return new Promise((resolve) => {
setTimeout(() => {
resolve({ price: 100 });
}, Math.random() * 5000);
});
}
async function fetchPriceWithTimeout(tickerSymbol: string): Promise<number> {
const stock = await Promise.race([
fetchData(), // returns `Promise<{ price: number }>`
asyncTimeout(3000), // returns `Promise<never>`
]);
// stock is now of type `{ price: number }`
return stock.price;
}
Promise.race
is a static method of thePromise
object in JavaScript, used to handle multiple Promise instances and return a new Promise instance. This new Promise instance will complete or reject when the first input Promise instance completes or rejects.
fetchData
is a simulated data request function, which could be an API request in actual development. The TypeScript compiler views the return type of the race
function as Promise<{price: number}> | Promise<never>
, so the type of stock
is {price: number}
. This is an example of using the never
type.
Here's another code example (source from the internet):
type Arguments<T> = T extends (...args: infer A) => any ? A : never
type Return<T> = T extends (...args: any[]) => infer R ? R : never
function time<F extends Function>(fn: F, ...args: Arguments<F>): Return<F> {
console.time()
const result = fn(...args)
console.timeEnd()
return result
}
function add(a: number, b: number): number {
return a + b;
}
const sum = time(add, 1, 2); // Call the time function to measure the execution time of the add function
console.log(sum);
// Output:
// [0.09ms] default
// 3
This example uses the never
type to narrow the result of conditional types. In type Arguments<T>
, if the input generic T
is a function, an inferred type A
will be generated from its parameter types as the type when the condition is met. In other words, if we input something that's not a function, the TypeScript compiler will eventually get the never
type as a fallback.
Therefore, when defining the time
function, we can use these two conditional types with generics, ultimately allowing the time
function to infer the final return value type through the type of the input function add
: sum
is of type number
.
I'm not sure if you need to write these type definitions in your work, but this is TypeScript.
We can see similar type declarations in the official source code:
/**
* Exclude null and undefined from T
*/
type NonNullable<T> = T extends null | undefined ? never : T;
Here, the conditional type distributes the judgment type to each union type when the input generic is a union type.
// if T = A | B
T extends U ? X : T == (A extends U ? X : A) | (B extends U ? X : B)
So the resolution of NonNullable<string | null>
is as follows:
NonNullable<string | null>
// The conditional distributes over each branch in `string | null`.
== (string extends null | undefined ? never : string) | (null extends null | undefined ? never : null)
// The conditional in each union branch is resolved.
== string | never
// `never` factors out of the resulting union type.
== string
Finally, the compiler recognizes it as the string
type.
A Brief Analysis of the unknown
Type
Any type of value can be assigned to a variable of unknown
type, so we can prioritize unknown
when considering using any
. Once we choose to use any
, it means we actively turn off TypeScript's type safety protection.
Alright, let's look at a code example:
function prettyPrint(x: unknown): string {
if (Array.isArray(x)) {
return "[" + x.map(prettyPrint).join(", ") + "]"
}
if (typeof x === "string") {
return `"${x}"`
}
if (typeof x === "number") {
return String(x)
}
return "etc."
}
This is a pretty print function that can take parameters of any type when called. However, after passing in, we need to manually narrow the type to use methods of specific type variables in the internal logic.
Moreover, if the data source is unclear, it can also prompt developers to perform necessary type validation and type checking, reducing runtime errors.
In addition, I've also seen type guard examples like the following, which I'd like to share:
function func(value: unknown) {
// @ts-expect-error: Object is of type 'unknown'.
value.test('abc');
assertIsRegExp(value);
// %inferred-type: RegExp
value;
value.test('abc'); // OK
}
/** An assertion function */
function assertIsRegExp(arg: unknown): asserts arg is RegExp {
if (! (arg instanceof RegExp)) {
throw new TypeError('Not a RegExp: ' + arg);
}
}
For parameters of unknown type, we can use the assertIsRegExp
function to assert the type. If the input parameter matches the type, no error will be thrown. In the lower half of func
, the compiler receives the assertion signal and can directly use the test
method.
The difference between this approach and if/else
is that when developers write if/else
, they need to explicitly write code for when the type is not as expected. Otherwise, when the type doesn't match, there might be a lack of runtime information, causing the code under the correct type condition not to execute.
We can't ensure that developers will always write handling logic for when the type is not as expected, so using type assertion guards is also a viable strategy. It will report an error at runtime, and if the frontend project runs under an effective monitoring system, error messages can be received for troubleshooting.
If you like this type of type guard, you can use libraries like elierotenberg/typed-assert: A typesafe TS assertion library to reduce workload. It has written functions like assertIsRegExp
for us.
If you prefer explicit if/else
conditional judgments, you can also use ultra-lightweight type checking libraries like mesqueeb/is-what: JS type check (TypeScript supported) functions like isPlainObject() isArray()\
etc. A simple & small integration..
If you don't want to introduce other libraries, then you can only write type checking code yourself. But if you write it yourself, be careful. Look at the following code:
// 1)
typeof NaN === 'number' // true
// π€ ("not a number" is a "number"...)
// 2)
isNaN('1') // false
// π€ the string '1' is not-"not a number"... so it's a number??
// 3)
isNaN('one') // true
// π€ 'one' is NaN but `NaN === 'one'` is false...
This is just a NaN
special case, but this is JavaScript.
Alright, see you next time.
Top comments (0)