Given a function with a parameter of different types, how do I find out which type was passed to the function?
Example
interface SomeCustomInterface {
title: string
}
interface OtherCustomInterface {
subtitle: string
}
interface A {
value: string
}
interface B {
value: number
}
interface C {
value: SomeCustomInterface
}
interface D {
value: OtherCustomInterface
}
function doSomething(parameter: A | B | C | D): string {
switch(parameter.type) {
// I know the cases are not valid TS. What should I do instead?
case A:
return parameter.value
case B:
return parameter.value.toString()
case C:
return parameter.value.title
case D:
return parameter.value.subtitle
}
}
I know that there are type guards but I have concerns with those
They need to be able to uniquely identify each type. I see that some people add a property
kind
ortype
which allows them to identify a type in order to type guard it. This seems like a lot of overhead and boilerplate to me though.You need to write a custom function for each type like
type is A
ortype is B
which again would lead to massive overhead in my context.
What is the appropriate way to approach this in typescript?