amdev
amdev

Reputation: 7460

How to use `some` to partially check items in object using TypeScript

I have an object:

interface MYInterface {
  aaa: number;
  bbb: number;
  ccc?: number | undefined;
}

const myObject: MYInterface = {
  aaa: 0,
  bbb: 0,
  ccc: 132,
};

I want to check if some keys in this object, satisfy a condition! I'm using Array.some(...) like below:

const res = ['aaa', 'bbb'].some((key) => myObject[key] > 0)

but for myObject[key] I'm getting a TypeScript error about:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'INxStateCounts'.
  No index signature with a parameter of type 'string' was found on type 'INxStateCounts'.

I know that what am I trying to do is checking array of strings (keys) with objects but my array contains those keys in string.

I have tried to cast key as keyof MYInterface but no luck! I was getting so many other errors. How can I fix this?

Also my object is very big, here I use 3 properties to demonstrate the issue.

Just in case if you want to test.

Upvotes: 1

Views: 697

Answers (4)

samchan0221
samchan0221

Reputation: 96

You can add as const to make it a tuple type. Then, the type of key argument will become 'aaa'|'bbb' instaed of string/any.

const res = (['aaa', 'bbb'] as const).some((key) => myObject[key] > 0)

Upvotes: 0

Emilio Lucas Ceroleni
Emilio Lucas Ceroleni

Reputation: 1608

If you use object index signature you might get what you are looking for. Try:

interface MYInterface {
  [key:string]: number;
}
...

Other ways to approach this: How to dynamically assign properties to an object in TypeScript

Upvotes: 0

Riadh Adrani
Riadh Adrani

Reputation: 615

You can write something like this:

const keys : Array<keyof MYInterface> = ['aaa', 'bbb']

const res = keys.some((key) => (myObject[key] !== undefined && myObject[key]! > 0))

for some reason the bang ! operator is needed despite undefined checking.

Upvotes: 1

Anton Marinenko
Anton Marinenko

Reputation: 3002

Just make more concrete typing in your code, like this:

function someOf<T>(keys: (keyof T)[], obj: T): boolean {
  return keys.some((key) => obj[key] > 0)
}

const res = someOf(['aaa', 'bbb'], myObject);

Upvotes: 3

Related Questions