9

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]);

1 Answer 1

11

I don't think there is a way to type the result of Object.values other than using the as keywords:

const getKeyInfo = (keyCode: ControlKey): [Axis, Axis] =>
  Object.values(keyCodeToAxis[keyCode]) as [Axis, Axis];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.