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?