-1

I want to use Array.prototype.includes method in my ts file like.

const id = this.selectedItem.id;
ids.includes(id);

Where ids is an array of numbers. I always get a compilation error: Argument of type 'number' is not assignable to parameter of type 'number & string'

When explicitly transform id to be a number Number(id), then I also see Type number is not assignable to type string. And when I explicitly transform id to be a string id.toString() then I can see Type string is not assignable to type number.

It is overwhelmig. How includes method can be used in TypeScript? How to use it in my example?

[Edit] Extended example:

    interface State extends EntityState<IItem> {}

    this.stateSubscription = this.store.select((state: State) => state.items).subscribe(
        val => {
            const selectedId = this.selectedItem ? this.selectedItem.id : null;
            val.ids.includes(selectedId);
    }));

val.ids.includes(selectedId as any) also doesn't work.

krzyhub
  • 6,285
  • 11
  • 42
  • 68

1 Answers1

0

You have declared ids as number[] & string[]

This means that the parameters you provide to the methods should be of type number[] & string[].

Try declaring it as number[] | string[], which is one of either, instead of both.

  • Probably you have a right, but this interface is an `ngrx/entity` predefined thing. I tried `const ids: string[] | number[] = val.ids;` but with no results. – krzyhub May 31 '19 at 08:06
  • Tried `ids.includes(selectedId as any)` but: `Cannot invoke an expression whose type lacks a call signature. Type '((searchElement: string, fromIndex?: number) => boolean) | ((searchElement: number, fromIndex?: number) => boolean)' has no compatible call signatures.` – krzyhub May 31 '19 at 08:10
  • @krzyhub could you please provide a [mcve] of your issue ? –  May 31 '19 at 08:13
  • @krzyhub I'm not talking about an extended example but about a [mcve] that you make on https://stackblitz.com : without the context in which you're working (libraries, effects, etc.) , I can't really help you more than that –  May 31 '19 at 08:22
  • I think that this case is not worth it. I will try something else than `Array.prototype.includes`, because TS just sucks. Thank you for your efforts. – krzyhub May 31 '19 at 08:26