I've created a few interfaces that reflect a function that potentially returns 3 different objects based on a passed in enumeration, and I'm trying to add typings to the function that returns them.
interface SummaryData {
summary: string,
summaryData: number
}
interface ConfigurationData {
configuration: string,
configurationData: number[]
}
interface StatusData {
status: string,
statusData: string
}
enum ViewTypeEnums {
summary = 1,
configuration = 2,
status = 3
}
function getInfo(viewType: ViewTypeEnums): SummaryData | ConfigurationData | StatusData {
if(viewType == 1){
return {
summary: "this is a summary",
summaryData: 1
}
} else if (viewType == 2){
return {
configuration: "this is configuration data",
configurationData: [1,2,3]
}
} else {
return {
status: "this is status data",
statusData: "data"
}
}
}
At the moment I'm using type parameters and pass in the expected return type when I call the function.
I know that I can instead use a type parameter to determine the return type, but it seems a little verbose/redundant to have to specify the expected data twice, and seems like there would be a better/more elegant way.
getInfo<SummaryData>(1) vs just having getInfo(1) with an inferred return type of SummaryData