As a newcomer to TS, I'm struggling to grasp why TS believes that
Object.values(keyCodeToAxis[keyCode])
could potentially result in an array with less than 2 elements.
type ControlKey = "KeyQ" | "KeyW" | "KeyE" | "KeyA" | "KeyS" | "KeyD";
type Axis = "x" | "y" | "z";
interface AxesForKey {
unchangingAxis: Axis;
increasingAxis: Axis;
}
const keyCodeToAxis: Record<ControlKey, AxesForKey> = {
"KeyQ": {
unchangingAxis: "z",
increasingAxis: "y",
},
"KeyW": {
unchangingAxis: "x",
increasingAxis: "y",
},
"KeyE": {
unchangingAxis: "y",
increasingAxis: "x",
},
"KeyA": {
unchangingAxis: "y",
increasingAxis: "z",
},
"KeyS": {
unchangingAxis: "x",
increasingAxis: "z",
},
"KeyD": {
unchangingAxis: "z",
increasingAxis: "x",
},
};
/**
* Obtain the axes associated with the key being pressed
* @param {String} keyCode - evt.code of the key being pressed
* @returns {[String, String]}
*
* @example
* // output will be ["x", "y"]
* getKeyInfo('KeyW');
*/
const getKeyInfo = (keyCode: ControlKey): [Axis, Axis] =>
// The error message Type 'any[]' is not assignable to type '[Axis, Axis]' suggests that the target expects exactly two elements, but the source might have fewer
Object.values(keyCodeToAxis[keyCode]);