【问题标题】:How to pass interface to react useState in a functional component?如何在功能组件中传递接口以响应 useState?
【发布时间】:2020-06-13 19:05:20
【问题描述】:

我正在尝试向下传递接口以响应 useState,但这样做时我收到此错误。

'""' 类型的参数不能分配给类型参数 '编辑配置文件界面 | (() => EditProfileInterface)'

我做错了什么?我试图告诉打字稿检查 bio 是一个字符串。我知道我可以做类似useState<String>('') 的事情,但我想使用一个界面。

interface EditProfileInterface {
    bio: string;
    gravatar: string;
}

function EditProfile(props: any) {
    const [bio, setBio] = useState<EditProfileInterface>('');
    .....
}

【问题讨论】:

  • 这可能是由数组解构中的bug 引起的。

标签: reactjs typescript


【解决方案1】:

你应该这样做:

const [bio, setBio] = useState<EditProfileInterface['bio']>('');

这将缩小您在 EditProfileInterface 接口中需要的特定属性 (bio)。

【讨论】:

    【解决方案2】:

    您传递一个字符串 ('') 作为默认值,但使用 EditProfileInterface 作为类型。 EditProfileInterface 是一个接口,定义了两个字符串属性。

    【讨论】:

      猜你喜欢
      • 2020-05-30
      • 1970-01-01
      • 1970-01-01
      • 2019-02-27
      • 2021-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-27
      相关资源
      最近更新 更多