如何处理 ts 错误 - 目标需要 2 个元素,但源可能更少

Але*_*нко 10 typescript

我是TS新手。我不明白为什么 TS 认为Object.values(keyCodeToAxis[keyCode])可以返回一个长度小于 2 个元素的数组。

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]);
Run Code Online (Sandbox Code Playgroud)

小智 12

Object.values我认为除了使用关键字之外没有其他方法可以输入结果as

const getKeyInfo = (keyCode: ControlKey): [Axis, Axis] =>
  Object.values(keyCodeToAxis[keyCode]) as [Axis, Axis];
Run Code Online (Sandbox Code Playgroud)