TypeScript key and index compatibility?
I have a method signature that expects a second argument keyof Array<...>
. Since the interface Array
defines an index [n: number]: T;
, I would expect some way to refer to some index in a method.
But I cannot find how to do this. I tried the following:
MyMethod(myArray, 0); // Argument of type '0' is not assignable to parameter of type ...
MyMethod(myArray, [0]); // Argument of type 'number[]' is not assignable to parameter of type ...
MyMethod(myArray, '0'); // Argument of type '"0"' is not assignable to parameter of type ...
MyMethod(myArray, '[0]'); // Argument of type '"[0]"' is not assignable to parameter of type ...
And nobody works.
source to share
You can always try:
function myFun<T>(arr: Array<T>, index: number) {
return arr[index];
}
keyof Array<...>
It refers to all the property names arrays, such as length
, toString
, push
, pop
etc. Number indices are not part of the interface Array
in the same way, they are a search type :
interface Array<T> {
length: number;
toString(): string;
... etc ...
[n: number]: T;
}
Consider a simpler interface:
interface Arr<T> {
[n: number]: T;
}
const variable: keyof Arr<number>; // variable is of type "never"
This is actually a flaw in the language. See also this issue on GitHub :
We cannot list all these numeric string literals (efficiently).
keyof Container<T>
will benumber | numericString
cnumericString
as the type of all numeric string literals with the corresponding number literal.number | string
will not be correct because not everyonestring
isnumericString
. In addition, not every string is a character digit sequencenumbericString
because a number has a maximum and minimum value.
source to share