在react typescript中将数组作为参数传递给函数时遇到类型问题

68de4m5k  于 2023-03-04  发布在  TypeScript
关注(0)|答案(1)|浏览(244)

当在react类型脚本中将数组作为参数传递给函数时,我遇到沿着一些类型问题。如何在函数中将数组作为参数传递时为数组赋值?
我正在使用ramda包来执行一些操作。
下面是代码

import { add } from "ramda";

// score type need to define here
const calcScore = (score) => {
  const scores = {}
  const id = score[0]
  newValue = score[1]
  currentValue = scores[id] || 0; // getting issue here Element implicitly has an 'any' type because expression of type 'any' can't be used of index type
  scores[id] = add(currentValue, newValue)
}

得分数组如下所示['ES ',200]。
我还遇到了另一个类型问题,如“undefined”在下面的代码中不能用作索引类型

import { add, propOr } from "ramda";

type actioProps = {
  ansId: string;
  ansValue: string;
}

type AppState = {
  submitted: object
}

const answer = (appState: AppState, action: actionProps) => {
  const id = prop('id')(getQues(appState, action.ansId))
  const value = props('submitted')(appState);

  //here I am getting  'undefined' cannot be used as an index type for the id
  value[id] = {
    [action.ansId]: action.ansValue
  }

  // another type issue like answers is of type unknown
  const answers = propOr({}, id)(value);
  answers[action.ansId] = action.ansValue;
}

在上面相同的代码中,我得到了其他类型的问题,比如答案是未知类型的。

q9rjltbz

q9rjltbz1#

问题是prop('id')(getQues(appState, action.ansId))的类型可以是undefined。请尝试将数组访问封装到type guard if语句中:

if (value !== undefined) {
  value[id] = {
    [action.ansId]: action.ansValue
  }
}

相关问题