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

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

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.

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay