Ionic 将基于类的JS useState数组转换为TypeScript挂钩问题

t40tm48m  于 2022-12-08  发布在  Ionic
关注(0)|答案(1)|浏览(144)

I've been working with React / TypeScript for a few days and am teaching myself by doing a small project. As part of that I am currently converting some class based code into hooks.
I have the following (JS) class based code that I don't know how to convert to use in a hook with TypeScript:

this.setState({
  data: [
    ...this.state.data,
    {
      chx: chx,
      type: type,
      bin: bin,
      ascii: ascii,
    },
  ],
});

In my hook based equivalent I know that I would use setData(); for a simple state. But, how do I convert the example above? My attempt (below) is clearly wrong, as I'm getting the error: Type '{ chx: unknown; type: string; bin: string; ascii: string; }' is not assignable to type 'never'. But I'm stuck for what I should do next to try and resolve this:

setData([
  ...data,
  {
    chx: chx,
    type: type,
    bin: bin,
    ascii: ascii,
  }
])

Update

I got this working by changing my useState declaration from:

const [ data, setData ] = useState([]);

to

const [ data, setData ] = useState<any>([]); //{type: read/write/notify/error, bin: 8 int binary, ascii: ASCII Value}

However, I realise this just defeats the object of using TypeScript. So, my next move based on @tomleb3 answer was to create an interface for data like so:

const [ data, setData ] = useState<DataType>([]); //{type: read/write/notify/error, bin: 8 int binary, ascii: ASCII Value}
  
  interface DataType{
    chx: any,
    bin: string,
    type: string,
    ascii: string
  }

but this gives an error:
Argument of type 'never[]' is not assignable to parameter of type 'DataType | (() => DataType)'. Type 'never[]' is not assignable to type '() => DataType'. Type 'never[]' provides no match for the signature '(): DataType'.
I don't know how to progress from here as removing the [] useState declaration then pushes the error down to wherever I use a setData() call with the following error:
Argument of type 'any[]' is not assignable to parameter of type 'SetStateAction<DataType | undefined>'. Type 'any[]' is not assignable to type '(prevState: DataType | undefined) => DataType | undefined'.

1cosmwyk

1cosmwyk1#

您收到的错误是Typescript错误,而不是React错误。
您的代码非常好,但是在使用Typescript时,我们需要像输入其他内容一样输入状态。
例如,它可能如下所示:

interface State {
   key1: string,
   key2: number,
   key3: boolean,
}

function myComponent() {
   const [state, setState] = useState<State>({
      key1: 'test',
      key2: 42,
      key3: false,
   })
}

这允许Typescript知道您的状态结构,从而使它能够应用相关的类型保护和限制。

相关问题