I struggle to understand why typescript is not happy with the typing of my json:
const myjson = {
"cube": {
"points":
[[-100, -100, -100],
[ 100, -100, -100],
],
"triangles":
[[0,1,2,"rgba(255,255,127,0.3)"],
[2,3,0,"rgba(255,255,127,0.3)"]
]
},
"pyramid": {
"points":
[[ 0, -100, 0],
[ 100, 100, -100],
],
"triangles":
[[0,1,2,"rgba(255,255,127,0.3)"],
[0,2,3,"rgba(0,255,127,0.3)"],
]
}
}
interface Data3D {
[k: string]: {
points: number[][];
triangles: [number, number, number, string][];
}
}
const make3D = (jsondata: Data3D) => {
console.log(jsondata);
}
make3D(myjson);
Typescript complains about the triangles type:
Types of property 'triangles' are incompatible.
Type '(string | number)[][]' is not assignable to type '[number, number, number, string][]'.
Type '(string | number)[]' is not assignable to type '[number, number, number, string]'.
Target requires 4 element(s) but source may have fewer.(2345)
I type using a custom type [number, number, number string] but Typescript reports it could have fewer elements ?
if I change the type of triangles to :
triangles: (number | string)[][];
it works.
why can't I type it more precisely like that ? :
triangles: [number, number, number, string][];