反应/排字:键入提示任何不起作用



>我有一个非常简单的反应组件,名为:github.tsx

在其中,我有以下代码:

import React from 'react'
import axios from 'axios'
class Github extends React.Component<{any, any}>{
state = {
user: []
}
getRepoUser = async () => {
let res = await axios.get('https://api.github.com/users/example');
this.setState({
user: res.data
})
}
componentDidMount () {
this.getRepoUser()
}
render () {
const { user } = this.state
return (
<div>
<h2>{user.login}</h2>
<p> repos: {user.public_repos} </p>
<p>followers: {user.followers}</p>
<img src={user.avatar_url} alt=""/>
</div>
)
}
}
export default Github

我以为通过向组件添加<{any, any}>,我不会有任何问题,但我看到这样的控制台错误:

backend.js:6 /home/example/tuts/components/github.tsx
./components/github.tsx
[tsl] ERROR in /home/example/tuts/components/github.tsx(35,24)
TS2339: Property 'avatar_url' does not exist on type 'any[]'.

我得到上述错误 4 次,分别为user.loginuser.public_reposuser.followersuser.avatar_url

创建组件时,传递给React.Component的第一个类型是 props 类型,而第二个类型定义状态类型:

interface IState {}
interface IProps {}
class Component extends React.Component<IProps, IState> {

执行此操作时:

class Github extends React.Component<{any, any}>

您只是将组件 props 类型定义为具有 2 个属性的对象,这两个属性都称为any不起作用。

您的组件类型需要如下所示:

class Github extends React.Component<any, any>

此外,推断的state.user类型是一个数组,因为初始状态为:

state = {
user: []
}

这就是为什么您会收到有关user.login的错误,user.public_repos...

您可以像这样键入状态:

interface IState {
user: User;
}
interface User {
login: string;
public_repos: string;
followers: string;
avatar_url: string;
}
class Github extends React.Component<any, IState> {
public state = {
user: {
login: "",
public_repos: "",
followers: "",
avatar_url: "",
},
};
public getRepoUser = async () => {
const res = await axios.get<User>("https://api.github.com/users/example");
this.setState({
user: res.data,
});
}
...
}

你犯了一个语义错误。虽然您的程序在语法上是有效的,但它并不意味着您看起来想要的。

关键的一点是,在TypeScript中,声明的形式是

<name> [: type]

也就是说,名称排在第一位,并且始终是必需的,如果需要,可以后跟类型注释。

因此,如果我写,

type Props = {
any
};

我正在声明一个带有名为any的属性的类型。以上相当于

type Props = {
any: any
};

因为我没有类型注释,也没有上下文来推断它。

此外,我写道,

type Props = {
any,
any
};

我有一个声明的成员名为any两次,一个错误。

您可能打算为PropsState类型参数指定类型any,如下所示。

class Github extends React.Component<any, any> {
}

但是您改为为Props指定了类型{any, any},并且没有为State指定类型。

这有多种原因:

  1. React.Component接口接受两种类型,React.Component<P, S>其中 P 是 props 的类型,S 是状态的类型。它也可以接受一个单一的类型,即只是P。这就是您正在发生的事情,您将类型 P 定义为对象{any, any}(打字稿应该抱怨它,因为您指定了重复键(。这意味着您根本没有为状态提供类型。从 DefinetelyTyped 应该是任何。

  2. 您是在类上显式定义state,因此 TypeScript 将它的类型从定义中推迟。state.user是一个数组,因此此元素上没有avatar_url;

要解决此问题,您可以尝试在定义时明确声明state是任何

state: any = {
user: []
}

更好的解决方案是实际定义状态的类型或接口,而不使用任何类型或接口。 应避免any,尤其是在为应用程序编写的代码中。

您可以定义类似用户的类型或接口:

type User = {
name: string,
avatar?: string
}
// or 
interface IUser {
name: string,
avatar?: string
}

React.Component<{any, any}>中的"Typehint"与状态类型无关,这是您指定的道具类型。查看 react 组件的声明:declare class React$Component<Props, State = void> { ...

最新更新