我正在迁移一个带有TypeScript的React项目,以使用钩子功能(React v16.7.0-alpha),但我不知道如何设置解构元素的类型。

这里有一个例子:

interface IUser {
  name: string;
}
...
const [user, setUser] = useState({name: 'Jon'});

我想强制user变量为IUser类型。我唯一成功的尝试是分两个阶段进行:输入,然后初始化:

let user: IUser;
let setUser: any;
[user, setUser] = useState({name: 'Jon'});

但我相信有更好的办法。另外,setUser应该初始化为一个函数,该函数接受IUser作为输入,并且不返回任何东西。

另外,值得注意的是使用const [user, setUser] = useState({name: 'Jon'});没有任何初始化工作很好,但我想利用TypeScript的优势来强制init上的类型检查,特别是如果它依赖于一些道具。

谢谢你的帮助。


当前回答

https://fettblog.eu/typescript-react/hooks/

// import useState next to FunctionComponent
    import React, { FunctionComponent, useState } from 'react';
    
    // our components props accept a number for the initial value
    const Counter:FunctionComponent<{ initial?: number }> = ({ initial = 0 }) => {
      // since we pass a number here, clicks is going to be a number.
      // setClicks is a function that accepts either a number or a function returning
      // a number
      const [clicks, setClicks] = useState(initial);
      return <>
        <p>Clicks: {clicks}</p>
        <button onClick={() => setClicks(clicks+1)}>+</button>
        <button onClick={() => setClicks(clicks-1)}>-</button>
      </>
    }

其他回答

使用这个

const [user, setUser] = useState<IUser>({name: 'Jon'});

请参见DefinitelyTyped中对应的类型

class Form {
    id: NullNumber = null;
    name = '';

    startTime: NullString = null;
    endTime: NullString = null;

    lunchStart: NullString = null;
    lunchEnd: NullString = null;

    [key: string]: string | NullNumber;
}

export const EditDialog: React.FC = () => {
    const [form, setForm] = useState<Form>(new Form());


    const inputChange = (e: ChangeEvent<HTMLInputElement>) => {
        const element = e.target;
        setForm((form: Form) => {
            form[element.name] = element.value;
            return form;
        })
    }
    return (
        <Box pt={3}>
            <TextField
                required
                name="name"
                label="Наименование"
                defaultValue={form.name}
                onChange={inputChange}
                fullWidth
            />
        </Box>
    );
}

首先useState取一个泛型,这将是你的IUser。如果您希望传递useState返回的第二个解构元素,则需要导入Dispatch。考虑你的例子的扩展版本,它有一个点击处理程序:

import React, { useState, Dispatch } from 'react';

interface IUser {
  name: string;
}

export const yourComponent = (setUser: Dispatch<IUser>) => {

    const [user, setUser] = useState<IUser>({name: 'Jon'});

    const clickHander = (stateSetter: Dispatch<IUser>) => {
        stateSetter({name : 'Jane'});
    }

    return (
         <div>
            <button onClick={() => { clickHander(setUser) }}>Change Name</button>
        </div>
    ) 
}

请看这个答案。

你也可以在之前声明初始状态,然后可以在任何你想要的时候调用它:

type User = typeof initUser;
const initUser = {name: 'Jon'}
...
const [user, setUser] = useState<User>(initUser);

关于I接口前缀:https://basarat.gitbooks.io/typescript/content/docs/styleguide/styleguide.html#interface

https://fettblog.eu/typescript-react/hooks/

// import useState next to FunctionComponent
    import React, { FunctionComponent, useState } from 'react';
    
    // our components props accept a number for the initial value
    const Counter:FunctionComponent<{ initial?: number }> = ({ initial = 0 }) => {
      // since we pass a number here, clicks is going to be a number.
      // setClicks is a function that accepts either a number or a function returning
      // a number
      const [clicks, setClicks] = useState(initial);
      return <>
        <p>Clicks: {clicks}</p>
        <button onClick={() => setClicks(clicks+1)}>+</button>
        <button onClick={() => setClicks(clicks-1)}>-</button>
      </>
    }