Array of only strings or only numbers
I can't seem to figure out how to work with an array that will be made of only strings or only numbers, basically something with type string[] | number[]
. On such an array I can't seem to call .push()
on it because the type for the arguments to .push()
will be never
.
My use case is this:
I have an interface like this
export interface Response {
numbers: Array<number>;
strings: Array<string>;
}
export type ResponseKey = keyof Response;
Then later if I index into a Response object
const response: Response = { numbers: [], strings: [] };
let key: ResponseKey;
// dynamicaly assign the key somehow ...
const value = response[key];
Now the type for value
is string[] | number[]
.
TypeScript infers every item type to string & number
which gives never
because these types have nothing in common.
You could split your code into two if
statements to narrow the key
to its actual type:
export interface Response {
numbers: Array<number>;
strings: Array<string>;
}
type ResponseKey = keyof Response;
const response: Response = { numbers: [], strings: [] };
declare let key: ResponseKey;
// dynamicaly assign the key somehow ...
if (key === 'numbers') {
const value = response[key]; // number[]
value.push(2);
}
if (key === 'strings') {
const value = response[key]; // string[]
value.push('test');
}
TypeScript playground