You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React TypeScript中传递数组作为函数参数的类型问题咨询

React TypeScript + Ramda 数组参数类型与对象索引类型问题解决

问题一:数组参数类型定义与对象索引报错解决

针对calcScore函数的类型问题,核心是明确数组参数的元组类型,同时给对象指定具体的索引结构:

import { add } from "ramda";

// 定义score的元组类型:第一个元素为字符串ID,第二个为数值分数
type ScoreTuple = [string, number];

const calcScore = (score: ScoreTuple) => {
  // 明确scores是键为string、值为number的对象
  const scores: Record<string, number> = {};
  const id = score[0];
  const newValue = score[1];
  // 使用??替代||,避免0被误判为假值
  const currentValue = scores[id] ?? 0;
  scores[id] = add(currentValue, newValue);
};

关键修正点

  • 用ScoreTuple元组类型约束数组参数,避免参数隐式为any
  • 用Record<string, number>定义scores结构,解决"索引类型不匹配"的报错
  • 替换||为??,处理数值0的边界情况更严谨

问题二:对象索引类型与unknown类型问题解决

针对answer函数的两个类型错误,需要明确嵌套对象的类型结构,同时约束Ramda工具函数的返回类型:

import { prop, propOr } from "ramda";

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

// 定义submitted的具体结构:外层键为问题ID,内层键为答案ID,值为答案内容
type SubmittedAnswers = Record<string, Record<string, string>>;

type AppState = {
  submitted: SubmittedAnswers;
};

// 明确getQues的返回类型,确保id为string类型
type Question = {
  id: string;
  // 其他问题字段...
};

const getQues = (appState: AppState, ansId: string): Question => {
  // 此处实现getQues的业务逻辑,确保返回包含id的Question对象
  return { id: "sample-question-id" };
};

const answer = (appState: AppState, action: ActionProps) => {
  const ques = getQues(appState, action.ansId);
  const id = ques.id; // 直接获取id,避免prop返回undefined的风险

  const value = appState.submitted;

  // 先初始化空对象,避免赋值时的类型报错
  if (!value[id]) {
    value[id] = {};
  }
  value[id][action.ansId] = action.ansValue;

  // 给propOr指定泛型,明确返回值为对象类型,消除unknown报错
  const answers = propOr<Record<string, string>>({}, id)(value);
  answers[action.ansId] = action.ansValue;
};

关键修正点

  • 替换模糊的object类型为SubmittedAnswers,明确嵌套对象的结构
  • 给getQues指定返回类型Question,确保id为string,解决"undefined不能作为索引"的报错
  • 给propOr添加泛型约束,明确返回值类型,消除answers的unknown类型问题
  • 修正笔误:Ramda中取单个属性的函数是prop而非props(props用于批量取属性)

内容的提问来源于stack exchange,提问作者James

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 17:53:01