我是React&Typescript的新手,试图弄清楚选择器是否可以返回自定义类型。
这是一个基本选择器,它返回类型为Map<string, any>
的用户:
选择器/user.ts
import { createSelector } from 'reselect';
import { TypedMap } from 'reducers';
import { User } from 'types/api';
const rawSelectUser = (state: TypedMap) => state.get('session');
const selectUser = () =>
createSelector(
rawSelectUser,
substate => substate.get('user')
);
export default selectUser;
我想知道是否可以返回我正在应用程序其他地方使用的类型User
:
types / api.ts
export class User implements Serializable<User> {
id!: number;
firstName!: string;
lastName!: string;
name!: string;
email!: string;
isActive!: boolean;
role!: UserRole;
metadata?: any;
}
最终,我希望我的.tsx文件使用types/api.ts
中的用户类型。但是此代码当前会产生以下错误:
index.tsx
...
const mapStateToProps = createStructuredSelector<TypedMap, LoginProps, User>({
user: selectUser()
});
const mapDispatchToProps = (dispatch: Dispatch<AnyAction>) =>
bindActionCreators(
{
postLogin,
checkUserPresent
},
dispatch
);
const withConnect = connect(
mapStateToProps,
mapDispatchToProps
);
const themedComponent = withTheme(withStyles(styles)(Login));
export default compose(withConnect)(themedComponent);
mapDispatchToProps = (dispatch: Dispatch<AnyAction>) =>
...生成此错误:
index.js:1437 /Users/username/sites/my-ui/src/containers/Login/index.tsx
TypeScript error in /Users/username/sites/my-ui/src/containers/Login/index.tsx(151,5):
Argument of type '{ user: OutputSelector<TypedMap, any, (res: Map<string, any>) => any>; }' is not assignable to parameter of type '{ id: ParametricSelector<TypedMap, LoginProps, number>; firstName: ParametricSelector<TypedMap, LoginProps, string>; lastName: ParametricSelector<TypedMap, LoginProps, string>; ... 6 more ...; fromState: ParametricSelector<...>; }'.
Object literal may only specify known properties, and 'user' does not exist in type '{ id: ParametricSelector<TypedMap, LoginProps, number>; firstName: ParametricSelector<TypedMap, LoginProps, string>; lastName: ParametricSelector<TypedMap, LoginProps, string>; ... 6 more ...; fromState: ParametricSelector<...>; }'. TS2345
149 | // }
150 | const mapStateToProps = createStructuredSelector<TypedMap, LoginProps, User>({
> 151 | user: selectUser()
| ^
152 | });
153 |
154 | const
答案 0 :(得分:0)
const getSession = (state: TypedMap) => state.get('session');
const selectUser = createSelector(
getSession,
(session): User => session.get('user')
)
请注意createSelector
的第二个参数上的类型断言
和
createStructuredSelector<TypedMap, LoginProps, { user: User }>