首页 > 解决方案 > 反应打字稿错误类型'{ id:数字;标题:字符串;函数():无效;}' 不可分配给类型 'null'

问题描述

我按照本教程尝试重新创建具有活动打开和关闭状态的按钮组,但是在使用打字稿时出现以下错误:

Type '{ id: number; title: string; function(): void; }' is not assignable to type 'null'.

代码:

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

const ButtonGroup: React.FunctionComponent = () => {
    
    const [active, setActive] = React.useState({
        activeObject: null,
        objects: [{
            id: 1 as number,
            title: '1' as string, 
            function() {
                alert('yes 1')
            }
            
        }, {
            id: 2 as number,
            title: '2' as string,
            function() {
                alert('yes 2')
            }
        }, {
            id: 3 as number,
            title: '3' as string,
            function() {
                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)} key={inner.id}>{inner.title}</Button>
                )
            })}
            </div>
        </>

    )
}

export default ButtonGroup;

有任何想法吗?

标签: reactjstypescript

解决方案


useState如果您不直接指定,将默认为参数的“类型”。

const [active, setActive] = React.useState({
  activeObject: null,
  /* ... */
});

所以在这种情况下,activeObject只能推断为存在null而没有别的。

相反,我建议定义一个typeorinterface并告诉useState它是状态对象的类型。

type AO = {
  activeObject: { id: number; title: string; function(): void; };
  /* and all of your other data */
}

然后

const [active, setActive] = React.useState<AO>({ /* ... */ });

将指定它active的类型是AO. 然后,您也不需要执行as numberor as string,因为这些类型将被要求AO类型。


推荐阅读