'typescript Record accepts array, why?
Can anyone explain why this compiles in typescript?
I tried some googling and looking it up in the typescript documentation but didn't find the answer.
type RecType = Record<string, any>
const arr: RecType = [1, 2, "three"] //or new Array(1, 2, 3)
console.log(arr) // [1, 2, "three"]
console.log(Array.isArray(arr)) // true
console.log(Object.keys(arr)) // ["0", "1", "2"]
Solution 1:[1]
After resting a little, coming back to the problem and looking a little deeper I think I understand it.
this is how Record is defined in typescript (from it's source code)
type Record<K extends keyof any, T> = {
[P in K]: T;
};
an array can be assigned to this because
keyofoperator will return the array's indices as the keys (similar to how Object.keys does).- the accessor
[P in K]: Tis valid for array becausearray["0"]is a valid way to access index 0 of the array (and so isarray[0]
I hope I got it right, feel free to make corrections.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mattia |
