Jayvee Embog
Jayvee Embog

Reputation: 47

typescript handle different types of return

how can i handle this? it always give me Property 'error' does not exist on type ''

here is my code

interface Error {
    error: true;
    message: string;
}
interface Person {
    fname: string;
    lname: string;
}

function(typesToReturn:string): Person | Error {
    if(typesToReturn == "1") return {error: true; message: "i am error"}
    return {fname: "foo"; lname: "bar"}
}

const a = function("1");
console.log(a.error) // Property 'error' does not exist on type 'Person'
console.log(a.fname) // Property 'fname' does not exist on type 'Error'

how can i fix it?

i dont want to set function(typesToReturn:string): any

also i dont want to use console.log((a as any).fname)

and i dont want // @ts-ignore

what is the other way?

acctually i want to use it like this

if(a.error) console.log("there's an error", a.message)
else  console.log("hooray")

Upvotes: 0

Views: 423

Answers (2)

Mahmoud Nasr
Mahmoud Nasr

Reputation: 642

interface Error {
        error: boolean;//<---type
        message: string;
    }
interface Person {
        fname: string;
        lname: string;
    }



let  f= function(typesToReturn:string):Error | Person{ //<<---variable function i.e assign function to avriable
    if(typesToReturn === "1"){
        return {error: true, message: "i am error"} as Error; // <<--- use as return Type
    } else{
        return {fname: "foo", lname: "bar"} as Person;  // <<--- use as return Type
    }
};


let a =  f("2");//<<---use case
console.log('error' in a? a.error:a.fname) //<<--- check for the key

Upvotes: 1

hoangdv
hoangdv

Reputation: 16127

You can create a type guard to make sure that an object is an Error.

function isError(pet: Person | Error): pet is Error {
  return (pet as Error).error !== undefined;
}

Then, just use this function to handle your function result:

function doSomething(typesToReturn: string): Person | Error { // avoid set name of a function is `function`
  if (typesToReturn == "1") {
    return { error: true, message: "i am error" } as Error
  }

  return { fname: "foo", lname: "bar" }
}

const result = doSomething("1");

if (isError(result)) {
  // now, result is a Error
  console.log(result.error);
} else {
  // now, result is a Person
  console.log(result.fname);
}

Upvotes: 0

Related Questions