Answer the question
In order to leave comments, you need to log in
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...
}
ids
in which there can be either only string or only number. IData
, I specified that id is of type either string or number. data
only with strings. doSomething1(dataIds)
, specifying an array with id as an argument. doSomething2(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'
только number
or только string
. Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question