gpt4 book ai didi

typescript - 类型 'user' 上不存在属性 'DefaultRootState'

转载 作者:行者123 更新时间:2023-12-04 16:38:38 30 4
gpt4 key购买 nike

情况

  • 我遇到了这个错误'user' does not exist on type 'DefaultRootState'。我试图解决它,但我没有想出解决方案。

这是我的 repo

错误

C:/Users/taiga/Github/Typescript/typescript-admin/admin/src/secure/components/Nav.tsx
TypeScript error in C:/Users/taiga/Github/Typescript/typescript-admin/admin/src/secure/components/Nav.tsx(44,50):
Property 'user' does not exist on type 'DefaultRootState'. TS2339

Nav.tsx

class Nav extends Component<{ user: User }> {
state = {
redirect: false
};

handleClick = async () => {
await axios.post('logout', {});

this.setState({
redirect: true
});
};

render() {
if (this.state.redirect) {
return <Redirect to={'/login'} />;
}

return (
<nav className="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0 shadow">
<ul className="my-2 my-md-0 mr-md-3">
<Link to={'/profile'} className="p-2 text-white">
{this.props.user.name}
</Link>
</ul>
</nav>
);
}
}

export default connect((state) => ({ user: state.user }))(Nav);

user.ts

mport { Role } from './role';

export class User {
id: number;
first_name: string;
last_name: string;
email: string;
role: Role;
permissions: string[];

constructor(
id = 0,
first_name = '',
last_name = '',
email = '',
role = new Role(),
permissions: string[] = []
) {
this.id = id;
this.first_name = first_name;
this.last_name = last_name;
this.email = email;
this.role = role;
this.permissions = permissions;
}

setUserReducer.ts

import { User } from '../../classes/user';

const setUserReducer = (
state = { user: new User() },
action: { type: string; user: User }
) => {
switch (action.type) {
case 'SET_USER':
return {
...state,
user: action.user
};
default:
return state;
}
};

export default setUserReducer;

最佳答案

问题在于 connect HOC 不知道 state 的类型是您特定应用程序状态的类型,而不仅仅是任何状态类型。当它不知道你的特定状态的类型时,它假定状态是类型DefaultRootState,即defined in the react-redux types package作为一个空对象 {}.

有多种方法可以解决这个问题。根据 types 包的建议,一种可能性是覆盖 DefaultRootState 的定义并将其替换为应用的实际状态接口(interface)。

This interface can be augmented by users to add default types for the root state when using react-redux. Use module augmentation to append your own type definition in a your_custom_type.d.ts file. https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation

另一种更容易实现的可能性是在 mapStateToProps 函数中声明预期的状态类型。

export default connect((state: {user: User}) => ({ user: state.user }))(Nav);

现在 typescript 知道你的 state 有一个 user 类型为 User 的属性。

您还可以在调用 connect 函数时为其设置通用参数,不过我建议使用之前的方法。

export default connect<{user: User}, {}, {}, {user: User}>((state) => ({ user: state.user }))(Nav);

关于typescript - 类型 'user' 上不存在属性 'DefaultRootState',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65387046/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com