What is unknown in Typescript


Borislav Hadzhiev

Fri Feb 19 20212 min read


Photo by Tom Robertson

With the unknown type we have to first check the type that's currently stored in the variable before we get typescript support.

When using the any type - typescript ignores anything we do, anything is permitted, but that's not what we want most of the time, most of the time we still want to have some type checking.

That's when unknown comes in - we tell typescript, hey we're going to get this value, but we don't know its type, so we are just going to check with a couple of if statements to track it down and use it safely, in the if blocks give us support for the particular type that is checked for.

For example in the below snippet we get an error:

let myString: string; let remoteData: unknown; remoteData = 'hello world'; myString = remoteData;

The reason for the error is myString has to be a string and remoteData is of type unknown therefore the assignment fails. An important distinction is, had we used any instead of unknown for the type of remoteData we wouldn't have gotten the error, because when we use any typescript provides no type checking for us.

The way to fix the error would be to conditionally check if the typeof remoteData is a string and only then proceed with the assignment:

let myString: string; let remoteData: unknown; remoteData = 'hello world'; if (typeof remoteData === 'string') { myString = remoteData; }

In the scope of the if block remoteData is guaranteed to be a string, therefore we can access all string methods on it, like for example toLowerCase.

Outside of the if block, however the type is still unknown.

So we have to conditionally check before we make assignments and call methods specific to a type when using the unknown type, it still provides a ton of functionality and type checking as opposed to the any type.

Unknown is the better type over any, when we don't know what type of value we're going to get, but we have an idea what we want to do with it. In those cases we can get type support in conditional blocks using the unknown type.

Add me on LinkedIn

I'm a Web Developer with TypeScript, React.js, Node.js and AWS experience.

Let's connect on LinkedIn

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee