return instance of interface without declaring a variable without casting

Issue

In typescript, you can define an interface and create an instance of it by declaring a variable of that interface type and setting the properties appropriately like this.

interface Thing{
  id: number,
  name: string
}

const thing: Thing = {
    id:1,
    name:'my thing'
}

However, if I have a method or function that returns that interface type I cannot figure out how to return an instance of it without first creating a variable to return.

So I can do this:

function getThing(): Thing {
  const thing: Thing = {
    id:1,
    name:'my thing'
  }
  return thing;
}

I can’t figure out, what if any, is the correct syntax to do this

function getThing(): Thing {  
  return: Thing = {
    id:1,
    name:'my thing'
  }
}

I know I can do this:

function getThing(): Thing {  
  return <Thing> {
    id:1,
    name:'my thing'
  };
}

But that removes some amount of type checking that I would rather remain.

Is it possible to return an instance of an interface without declaring a variable and without casting?

Solution

You can either return the instance directly

function getThing(): Thing {  
  return {
    id:1,
    name:'my thing'
  };
}

Or to specify explicitly that the instance is of type Thing via as operator:

function getThing(): Thing {  
  return {
    id:1,
    name:'my thing'
  } as Thing;
}

Note that in the 2nd example, adding the as Thing part is un-necessary

Answered By – Dorin Baba

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published