Issue
I want to use following API call createWorkout({ workoutName, userId });
. When I hover on userId, I get the warning: Type 'number | null' is not assignable to type 'number'. Type 'null' is not assignable to type 'number'.ts(2322)
.
const handleSubmit = async (e: FormEvent) => {
e.preventDefault();
console.log(workoutName);
try {
const response = await createWorkout({ workoutName, userId });
console.log(response);
} catch (err) {
console.log(err);
}
};
The reason for the problem is, I defined userId number or null in my ContextAPI.
interface IUserAuthenticationContext {
userToken: string | null;
setUserToken: React.Dispatch<React.SetStateAction<string | null>>;
userId: number | null;
setUserId: React.Dispatch<React.SetStateAction<number | null>>;
handleLogout: () => void;
}
The userId for the request is defined as number:
export interface CreateWorkoutRequest {
userId: number;
workoutName: string;
}
The reason is, when the createWorkout function is called, the userId cannot be null anymore.
Do you have any other solution than defining userId for the API as <number | null> ?
Defining userId in CreateWorkoutRequest solves the problem:
export interface CreateWorkoutRequest {
userId: number | null;
workoutName: string;
}
However I don't think it is a nice solution because at the time when the API is called the userId can not be null anymore.
Solution
You can use non-null assertion operator. This operator tells TypeScript that you are sure the value is not null or undefined at the point where you use it.
const handleSubmit = async (e: FormEvent) => {
e.preventDefault();
console.log(workoutName);
try {
const response = await createWorkout({ workoutName, userId: userId! });
console.log(response);
} catch (err) {
console.log(err);
}
};
Answered By - Chellappan வ
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.