gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 15:02:16 27 4
gpt4 key购买 nike

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

最佳答案

我认为没有办法输入 Object.values 的结果除了使用 as关键词:

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

关于typescript - 如何处理 ts 错误 - 目标需要 2 个元素,但源可能更少,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66780719/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com