小编Seb*_*ier的帖子

关于逻辑运算符&&的理解问题

我对本React.js教程中的代码段有疑问。我是JavaScript的初学者,所以如果这是一个愚蠢的问题,请原谅。

function calculateWinner(squares) {
  const lines = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
  ];
  for (let i = 0; i < lines.length; i++) {
    const [a, b, c] = lines[i];
    if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
      return squares[a];
    }
  }
  return null;
}
Run Code Online (Sandbox Code Playgroud)

此功能的目的是评估井字游戏的赢家。平方参数获取一个类型的九个值的阵列null"X""O"

假设数组的前三个值是"X",则if语句将解析为"X" …

javascript

2
推荐指数
1
解决办法
59
查看次数

如何从 TS 文字联合类型推断对象的键和值?

我有两种字符串的文字联合类型,并希望它们成为对象的可能的键和值。

export type AlarmKeyword = 'R1' | 'R2';

export type ResourceTypes = 'nktw' | 'rtw' | 'nef' | 'rth' | 'hlf' | 'dlk';
Run Code Online (Sandbox Code Playgroud)

新类型如下所示:

export type AlarmKeywordObject = {
  [P in AlarmKeyword]: { [T in ResourceTypes]: number };
};
Run Code Online (Sandbox Code Playgroud)

但 TS 现在抱怨这段代码:

      {
        R1: {
          rtw: 1,
        },
      }
Run Code Online (Sandbox Code Playgroud)

输入 '{ rtw: 数字; }' 缺少类型 '{ nktw: number; 的以下属性;rtw:数字;内夫: 数量;rth:数字;hlf:数字;dlk:数字;}':nktw、nef、rth、hlf、dlk

我如何确保密钥是可选的而不是所有密钥都是必需的?

谢谢你!

typescript union-types

2
推荐指数
1
解决办法
871
查看次数

标签 统计

javascript ×1

typescript ×1

union-types ×1