我试图更新我的状态的形式提交,但我得到了一个错误TypeScritp我是新的TS,我不知道如何修复它
enum ServiceTypeEnum {
Replace = 'replace product',
Fix = 'fix product',
}
interface IProductName {
name: string
serviceType: ServiceTypeEnum
}
const index: FC<Props> = ({ className, ...props }) => {
const [dataArray, setDataArray] = useState({})
const onSubmit: SubmitHandler<IProductName> = data => {
console.log(data.serviceType)
setDataArray(prev => [
...prev,
{
name: data.name,
type1: data.serviceType[0],
type2: data.serviceType[1],
id: Date.now(),
},
])
console.log(dArray)
if (data.serviceType.length !== 0 && data.name !== '') {
console.log(data)
} else {
alert('choose name and at least one type')
}
}
}
这里是我的错误TS2461: Type '{}' is not an array type
我也在努力
const [dataArray, setDataArray] = useState([])
但我得到了这个错误TS2345: Argument of type '(prev: never[]) => { name: string; type1: string; type2: string; id: number; }[]' is not assignable to parameter of type 'SetStateAction<never[]>'.Type '(prev: never[]) => { name: string; type1: string; type2: string; id: number; }[]' is not assignable to type '(prevState: never[]) => never[]'. Type '{ name: string; type1: string; type2: string; id: number; }[]' is not assignable to type 'never[]'. Type '{ name: string; type1: string; type2: string; id: number; }' is not assignable to type 'never'.
在JS中没有错误,但我不知道我搜索的typeScript格式,但我什么也没找到
1条答案
按热度按时间am46iovg1#
这一行:
const [dataArray, setDataArray] = useState({})
可能应该用数组初始化,并键入:
const [dataArray, setDataArray] = useState([] as Array<YourDataType>)
或者:
const [dataArray, setDataArray] = useState<Array<YourDataType>>([])
Typescript在数组没有显式类型化时抱怨的原因是Typescript不知道它是什么类型的数组,所以Typescript假设数组的类型是
never[]
/Array<never>
-一旦你向useState
或数组本身添加了一个类型,Typescript就能够理解它。