Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript. Check if method/property exists in the variable of unknown type

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?

like image 875
Vitaly Avatar asked Aug 28 '19 16:08

Vitaly


People also ask

How do you check if a property exists in an object TypeScript?

The hasOwnProperty() method will check if an object contains a direct property and will return true or false if it exists or not. The hasOwnProperty() method will only return true for direct properties and not inherited properties from the prototype chain.

How do you access unknown objects in TypeScript?

Use a user-defined type guard to check if a value with unknown type contains a property in TypeScript. The user-defined type guard consists of a function that checks if the specific property is contained in the object and returns a predicate.

How do you handle unknown types in TypeScript?

In Typescript, any value can be assigned to unknown, but without a type assertion, unknown can't be assigned to anything but itself and any. Similarly, no operations on an unknown are allowed without first asserting or restricting it down to a more precise type.

Does not exist on type object?

The "Property does not exist on type Object" error occurs when we try to access a property that is not contained in the object's type. To solve the error, type the object properties explicitly or use a type with variable key names.


1 Answers

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

like image 62
Johnny Zabala Avatar answered Sep 23 '22 03:09

Johnny Zabala