D
D
Demigodd2019-12-17 11:29:41
JavaScript
Demigodd, 2019-12-17 11:29:41

How to set type to only string or only number in Typescript?

There is a piece of code.

data: IData[] = [];

get ids(): (string | number)[] {
  return data.map((n) => n.id);
}

export interface IData {
  id: string | number;
  name: string;
}

/** (1) **/
// Set data only string ID.

doSomething1(this.ids);

doSomething1 = (ids: string[]) => {
  // do something...
}

/** (2) **/
// Set data only number ID.

doSomething2(this.ids);

doSomething2 = (ids: number[]) => {
  // do something...
}

There is an array idsin which there can be either only string or only number.
In the interface IData, I specified that id is of type either string or number.
Further, in one place of the application, I initialize the object dataonly with strings.
And I call the function doSomething1(dataIds), specifying an array with id as an argument.
Elsewhere I initialize with numbers only, and call the functiondoSomething2(dataIds)
// (2) Typescript ругаеться на функцию <b>doSomething2</b>.

Argument of type '(string | number)[]' is not assignable to parameter of type 'number[]'.
  Type '(string | number)[]' is not assignable to type 'number[]'.
    Type 'string | number' is not assignable to type 'number'.
      Type 'string' is not assignable to type 'number'

I clearly indicated that it can have a type только numberor только string.
So what is the problem and how to solve it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Robur, 2019-12-17
@Demigodd


use instead
string[] | number[]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question