In my code, I have two interfaces as below
export interface Temp{
message : string
}
export interface Temp1{
message1 : string
}
With code like this, useMutation(….) sends a request to the server and requests the result.
const {mutate, isLoading, data} = useMutation(authRepository.Login, {
onSuccess: (value: Temp | Temp1) => {
if(value instanceof Temp){
}
}
});
'Temp' only represents a type, but here it is corrupted by value.
I am curious about a simple way to check Temp and Temp1
3
Answers
The problem with your code is that you are using the
instanceof
with an interface.The
instanceof
operator check if a class is an instance of a class that is why you are having that error.Maybe you can change your interfaces to classes or just make some implementations of your interfaces
Type guard
How about create small function to determine interface.
And now you can use Temp1 interfce value in if sentence.
vscode screen shot
Reference
I think the following questions will be helpful
Interface type check with Typescript
In this case, the type of response is usually
Temp|Temp1
, but not always (e.g. the server changes, network issues…)you may need some validator like
zod
to ensure the content of the object is actuallyTemp1
:The
satisfies
format is just my preference, it can also be done by create the schema first, and use the schema to inference thetype
: