简体   繁体   中英

TypeScript - Filter by Generic Type

I have an object which has some values which are arrays and some which are not. I want to filter out the arrays and I saw this being done in a similar way as following, but I want it to be done with all arrays and in cases when it's not of type instead of cases when it's of type, not just pass a specific type. Can it be done?

Object.values(inputsOptions).filter((obj: any): obj is not Array => {
        return obj instanceof Array;
    }).forEach(obj =>{
        //Every object has style property but arrays do not
        obj.style = {marginLeft: "1em"};
    });

Just noticed I used obj is Array when I meant the exact opposite, but I have now changed it. Still, the problem remains.

There is no is not assertion in TypeScript, and also if there were, and obj is any but not Array , it does not mean it's an object with a style property.

If you know obj can only be an array or an object with a mutable style property, you can assert what you do have:

Object.values({})
  .filter((value: unknown): value is { style: unknown } => {
    return !Array.isArray(value);
  })
  .forEach((object) => {
    object.style = { marginLeft: "1em" };
  });

(Also you should use Array.isArray instead of instanceof Array , see this .)

Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM