DEV Community

Cover image for Unknown type in typescript
Rubin
Rubin

Posted on

3 2

Unknown type in typescript

The unknown type in typescript is a common type that you will likely to come across. It is a strict version of the
any type and interms of accepting data, it accepts any data type which is similar to nature of any type. However
there is a minor differences between them. Since an unknown type also can have multiple type, it forces to use type assertion before using the types function. To further clear , lets look an example

 function readAny(val: any){
     return val.trim();
}
Enter fullscreen mode Exit fullscreen mode

In the above example, we are using any type for the value. Since trim is a string function, this works well for string data. However on supplying numbers or booleans , we get a runtine error

The same example using unknown

 function readAny(val: unknown){
     return val.trim(); // typescript error at this line
}
Enter fullscreen mode Exit fullscreen mode

Typescript would throw a compile time error as we are using string function without type assertion. To fix it, the correct code would look like

 function readAny(val: unknown){

    if( typeof val === 'string')
     return val.trim();
}
Enter fullscreen mode Exit fullscreen mode

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (1)

Collapse
 
jonashdown profile image
Jon Ashdown • Edited

There are several problems with this. Even if we used 'val: string' we would not get real type safety i.e at runtime. To get runtime type safety we have to use typeof or instanceof which are JavaScript primitives, or use a validation library. So then we have another problem how do you unit test the behaviour of non-string input? In typescript the compiler will stop us from passing in a non-string so we resort to either using 'any' or 'undefined' or a long list of '|' separated types which defeats the purpose of typescript and makes the code less readable and does not get added to the production bundle. A JavaScript equivalent of the example given without the superfluous type declarations would be much simpler create, with the added advantage of it being easily testable.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more