I am creating an authentication flow with react redux and typescript. I setup my signup auth state interface and initial state
export interface User {
id: string;
username: string;
email: string;
social: Social;
userCourses: Course[];
enrolledCourses: Course[];
}
interface AuthState {
isAuth: boolean;
usernamesAndEmails: UsernameAndEmail[] | [];
currentUser: User | {};
isLoading: boolean;
error: object;
}
const signupInitialState: AuthState = {
isAuth: false,
usernamesAndEmails: [],
currentUser: {},
isLoading: false,
error: {},
};
I then have a component where I need to use the currentUser state to have the user create their username (if they signed up with google/facebook).
const { currentUser } = useSelector((state: RootState) => state.auth);
const onSubmit = (data: FormData) => {
dispatch(tryChangeUsername(currentUser, data));
};
But I am getting the error (Argument of type '{} | User' is not assignable to parameter of type 'User'. Type '{}' is missing the following properties from type 'User': id, username, email, social, and 2 more.). I'm not sure if I need to set up my interfaces or initial state differently or what. I think the issue is coming from the fact that current user can be an empty object (although it will not be in that component because that component will be a private route) but I'm not sure how to rectify the issue.
You should check whether currentUser is type User or {} before using its property
function isUser(object: User | {}): object is User {
return 'id' in object;
}
let currentUser: User | {};
if (isUser(currentUser)) {
// make something
currentUser.id;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.