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

如何修复TypeScript中‘null不能用作索引类型’的错误

解决方法

针对difficulty可能为null导致无法作为对象索引的问题,可以从以下几个方向处理:

1. 给difficulty设置默认值

直接在获取参数时,用空值合并运算符指定默认难度,同时通过类型断言让TypeScript认可这个值是合法的键:

const difficulty = searchParams.get("difficulty") as DifficultyType ?? "easy";

这样无论URL中是否存在difficulty参数,difficulty都会是"easy"、"medium"或"hard"中的一个,直接用作questions的索引就不会报错。

2. 初始化时自动补全URL参数

如果希望URL始终显示difficulty参数,可以用useEffect在组件挂载或参数为空时,自动设置默认难度到URL中:

import { useEffect } from 'react';

// ...其他代码

const difficulty = searchParams.get("difficulty");

useEffect(() => {
  if (!difficulty) {
    setSearchParams({ difficulty: "easy" });
  }
}, [difficulty, setSearchParams]);

这样后续获取difficulty时就不会出现null的情况,同时URL也会保持有参数的状态。

3. 使用时做安全兜底

在访问questions[difficulty]前做兜底处理,避免因为null导致报错:

const handlePageChange = () => {
  // 兜底到easy难度的题目
  const targetQuestions = questions[difficulty as DifficultyType] ?? questions.easy;
  if (currentPage + 1 < targetQuestions.length) {
    setCurrentPage(prevState => prevState + 1);
  }
};

这种方式适合不想修改URL参数,但需要确保代码安全执行的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 14:25:15