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

React TypeScript报错:类型'{id:number;title:string;function():void;}'不可分配给null

报错原因

TypeScript 默认会根据 useState 的初始值自动推导状态类型,你初始化时给 activeObject 赋值为 null,TS 就默认推导 activeObject 的类型固定为 null。后续你尝试将 objects 数组中类型为 { id: number; title: string; function(): void; } 的对象赋值给 activeObject,两者类型不匹配,因此触发类型报错。

修复方案

你需要主动给 useState 声明泛型,指定状态的完整类型,步骤如下:

  • 先定义按钮项的类型接口,同时建议不要用 function 作为属性名(属于 JS 保留关键字,容易引发歧义),可以改成 onClick 这类语义化名称
  • 给 useState 传入泛型,明确 activeObject 允许的类型为「按钮项类型 | null」

修改后的完整代码如下:

import React from 'react';
import Button from '../button/Button'

// 定义按钮项的类型
interface ButtonItem {
  id: number;
  title: string;
  onClick: () => void;
}

// 定义state的完整类型
interface ActiveState {
  activeObject: ButtonItem | null;
  objects: ButtonItem[];
}

const ButtonGroup: React.FunctionComponent = () => {
    
    const [active, setActive] = React.useState<ActiveState>({
        activeObject: null,
        objects: [{
            id: 1,
            title: '1', 
            onClick() {
                alert('yes 1')
            }
            
        }, {
            id: 2,
            title: '2',
            onClick() {
                alert('yes 2')
            }
        }, {
            id: 3,
            title: '3',
            onClick() {
                alert('yes 3')
            }
        }]
    })

    const toggleActive = (index: number) => {
        setActive({ ...active, activeObject: active.objects[index] })
    }

    function toggleActiveStyles(index: number) {
        if (active.objects[index] === active.activeObject) {
            return "btn-tertiary"
        } else {
            return "btn-tertiary-active"
        }
    }

    return (
        <> <div >
            {active.objects.map((inner, index) => {
                return (
                    <Button 
                      variant="btn btn-tertiary" 
                      className={toggleActiveStyles(index)} 
                      onClick={() => {
                        toggleActive(index)
                        inner.onClick() // 触发按钮绑定的自定义点击事件,不需要可以删除
                      }} 
                      key={inner.id}
                    >
                      {inner.title}
                    </Button>
                )
            })}
            </div>
        </>

    )
}

export default ButtonGroup;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 00:45:03