Home > Blockchain >  How to set the return type to be a specific type when a condition is met?
How to set the return type to be a specific type when a condition is met?

Time:09-09

I want to set the return type of the function to be a certain type when the argument is true

function getProfile({isPrivate: boolean}): privateProfile | publicProfile {
    if(isPrivate){
       // fetches private profile and returns it
       ...
       return fetchedPrivateProfile;
    } else {
      // fetches a public profile and returns it
      ...
      return fetchedPublicProfile;
    }
}

so when I specify the function with isPrivate set to true the editor knows that the return type is going to be privateProfile

const definitelyAPrivateProfile = getProfile({isPrivate:true});
//      ^ definitelyAPrivateProfile: privateProfile

CodePudding user response:

I put together an example of the use of function overloads for your problem case which you can experiment with at enter image description here

interface PrivateProfile {
  privateThings:string[]
}

interface PublicProfile {
  publicThings:string[]
}

const privateExample: PrivateProfile = {
  privateThings: ["local","shop","local","people"]
}

const publicExample: PublicProfile = {
  publicThings: ["pens","pig","pokie"]
}

function getProfile(options:{isPrivate: true}): PrivateProfile;
function getProfile(options:{isPrivate: false}): PublicProfile;
function getProfile(options:{isPrivate: boolean}) {
  const {isPrivate} = options;
    if(isPrivate){
       return privateExample;
    } else {
      return publicExample;
    }
}


{
  const result = getProfile({isPrivate:true})
}

{
  const result = getProfile({isPrivate:false})
}
  • Related