Dr. Jan-Philip Gehrcke
Dr. Jan-Philip Gehrcke

Reputation: 35731

Typescript: when would you use 'unknown' vs. 'object'?

I am still rather new to TypeScript and trying to work on my knowledge and intuition about when to use which types.

When would you use unknown vs. object?

From https://www.typescriptlang.org/docs/handbook/basic-types.html:

About object:

object is a type that represents the non-primitive type, i.e. anything that is not number, string, boolean, symbol, null, or undefined.

About unknown:

We may need to describe the type of variables that we do not know when we are writing an application. These values may come from dynamic content – e.g. from the user – or we may want to intentionally accept all values in our API. In these cases, we want to provide a type that tells the compiler and future readers that this variable could be anything, so we give it the unknown type.

Is unknown a strict superset of object?

Is unknown maybe precisely object + number + string + boolean + symbol + null + undefined? If not: what's missing -- precisely, or conceptually?

If the TypeScript version matters for answering this: let's assume 3.9 :-).

Upvotes: 4

Views: 5250

Answers (1)

Drag13
Drag13

Reputation: 5988

Don't mix together these two types. The object is kinda "real" type, it exists in runtime, it allows you to deal with instances of the Object. I would say it's just regular, normal type.

But unknown is a kinda different thing. It was created to guard operations with types that don't have a type at all. It denies any direct operations with this type:

const x:unknown = 5;
x+= 1; // Object is of type 'unknown'.

It also not exists in runtime, so you can't create an instance of unknown or something like this.

So, I would say that unknown is the opposite type to any defined type.

Upvotes: 3

Related Questions