0

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

Aleksandar
  • 844
  • 1
  • 8
  • 18
madol
  • 551
  • 2
  • 17
  • When you create a type with the `type` or `interface` keywords in typescript, they're completely removed after compilation. The compiled JavaScript has no notion of those things. You can use instanceof with instances created from classes. Otherwise, you have to think about how you would do in plain JavaScript – ShamPooSham Apr 02 '23 at 07:02

3 Answers3

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

Mr-peipei
  • 61
  • 2
0

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) {}
}
Diego Bascans
  • 1,083
  • 1
  • 6
  • 14
0

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>
Jerryh001
  • 766
  • 2
  • 11