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

为何类型为never[]的useState状态可赋值数据且无编译报错?

为什么useState初始化空数组为never[]却未触发类型错误?

问题背景

我知道向useState钩子传递空数组时,必须指定正确类型,否则TypeScript会推断为never[]。但我编写的以下组件却能正常运行——组件获取的数据类型为any,要存入类型为never[]的loadedUsers中,编译时未出现任何错误,VSCode里也无警告信息,这是为什么?

组件核心代码

const AllUsers: FC<AllUsersProps> = () => {
  const [isLoading, setIsLoading] = useState(true);
  const [loadedUsers, setLoadedUsers] = useState([]);

  useEffect(() => {
    UserService.getAllUsers()
      .then((response) => response.json())
      .then((data) => {
        console.log("users after retrieving data", data);

        setIsLoading(false);
        setLoadedUsers(data);
      });
  }, []);

渲染逻辑代码

if (isLoading) {
    return (
      <section>
        <p>Loading users</p>
      </section>
    );
  }

  return (
    <div className="row">
      <div className="col">
        <h3>Users table</h3>
        <UserTable users={loadedUsers} />
      </div>
      <div className="col">
        <h3>Find user by id</h3>
        <UserSearch />
      </div>
    </div>
  );
};

原因解析

  • any类型的兼容性:response.json()返回的data默认是any类型,TypeScript允许any赋值给任意类型(包括never[]),因此调用setLoadedUsers(data)不会触发类型错误。
  • 加载状态的守卫作用:初始状态下isLoading为true,此时loadedUsers是never[]但不会被渲染到页面;当isLoading切换为false时,loadedUsers已经被any类型的数据覆盖,而如果UserTable组件的users参数未严格定义类型(比如也是any),TypeScript不会检测到类型不匹配。
  • TypeScript配置的宽松性:如果项目的tsconfig.json中关闭了部分严格检查选项(比如strictNullChecks、noImplicitAny未开启),会进一步弱化类型校验,让这类潜在问题被忽略。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 05:30:43