skip to Main Content

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){
            
        }
    }
});

enter image description here
get an error

'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


  1. 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

    class TempImpl implements Temp {
      constructor(public message: string) {}
    }
    
    class Temp1Impl implements Temp1 {
      constructor(public message1: string) {}
    }
    
    Login or Signup to reply.
  2. Type guard

    How about create small function to determine interface.

    const isTemp1 = (value: Temp | Temp1): value is Temp1 => {
      return "message1" in value;
    };
    

    And now you can use Temp1 interfce value in if sentence.

        const handleSubmit = (tem: Temp| Temp1)=> {
            if(isTemp1(tem)){
                console.log(tem)
            }
        }
    

    vscode screen shot

    Reference

    I think the following questions will be helpful

    Interface type check with Typescript

    Login or Signup to reply.
  3. 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 actually Temp1:

    import { z } from "zod"
    
    const temp1Schema = z.object({
        message1: z.string()
    }) satisfies z.ZodType<Temp1>
    
    function onSuccess(value: unknown) {
        const result = temp1Schema.safeParse(value)
        if(result.success) {
            result.data // Temp1
        }
    }
    

    The satisfies format is just my preference, it can also be done by create the schema first, and use the schema to inference the type:

    type Temp1 = z.infer<typeof temp1Schema>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search