6

TS v3.x brought new type: unknown. But it's not very clear how to easily use this type instead of any. Example: you're using some 3rd party library which has no types. And you don't have time to write those types yourself. You need to handle some data provided by that library.

Before unknown:

function handle(data: any) {
   if (data && data.arrayProp && typeof data.arrayProp[Symbol.iterator] === 'function') {
       for (let x of data.arrayProp) {...}
   }
}

With unknown:

function handle(data: unknown) {
   // this line gives TS error: `data` is unknown type
   if (data && data.arrayProp && typeof data.arrayProp[Symbol.iterator]=== 'function') {  
...

Most docs in internet are using kind of instanceof ways to check what type data has. But i'm not really interested what type data has. Everything i want to know is if there's arrayProp there. that's it

How to do this with unknown type?

1 Answer 1

5

The thing with unknown is that you have to narrow its type before you can use it. You can use a custom type guard for this:

interface ArrayProp {
  arrayProp: []
}
function isArrayProps(value: unknown): value is ArrayProp {
  return !!value && !!(value as ArrayProp).arrayProp;
}

function handle(data: unknown) {
   if (isArrayProps(data) && typeof data.arrayProp[Symbol.iterator] === 'function') {
   }
}

Playground

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. So, in run time it will be equivalent code as in my samples. why then not to allow it to compile... most probably i stick to any type for now, too much boilerplate with unknown type IMO :-)
You are right. At runtime it will be pretty much the same. But I would still prefer the Typescript (boilerplate) way. The reason is that outside the if you are secure. You can't call data.blab or data.foo or even data.arrayProp again. By forcing you to add the boilerplate Typescript is forcing you to be very thoughtful about the way you will be accessing that unknown.
I'd love to use unknown. Boilerplate is not the most problematic thing about it. The thing is i don't get why not to allow to compile my second sample? i did all the checks which are necessary for code inside if block. And outside of if block you're still safe. I.e. i see no value in this boilerplate...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.