javascript - Typescript. Check if methodproperty exists in the variable of unknown type - Stack Overflow

TS v3.x brought new type: unknown. But it's not very clear how to easily use this type instead of

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?

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?

Share Improve this question edited Aug 28, 2019 at 16:59 Vitaly asked Aug 28, 2019 at 16:30 VitalyVitaly 1,0101 gold badge9 silver badges10 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745004894a4605719.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信