I'm new to TS. I can't understand why TS thinks that Object.values(keyCodeToAxis[keyCode])
can return an array of less than 2 elements long.
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",
},
};
/**
* Gets the axes corresponding to the pressed key
* @param {String} keyCode - evt.code of pressed key
* @returns {[String, String]}
*
* @example
* // returns ["x", "y"]
* getKeyInfo('KeyW');
*/
const getKeyInfo = (keyCode: ControlKey): [Axis, Axis] =>
// TS2322: Type 'any[]' is not assignable to type '[Axis, Axis]'.
// Target requires 2 element(s) but source may have fewer
Object.values(keyCodeToAxis[keyCode]);