I am currently working on building a function that can accept two different types of input.
type InputA = {
name: string
content: string
color: string
}
type InputB = {
name: string
content: number
}
type Input = InputA | InputB
As I try to implement this function to handle both types of inputs, my goal is to differentiate between the two based on whether they have the color
attribute present.
However, I keep encountering a compiler error:
function foo(input:Input){
const color = (input.color) ? input.color : undefined;
// ^
// | Property 'color' does not exist on type 'Input'.
// | Property 'color' does not exist on type 'InputB'.
...
}
I am aware that one solution would be to add a new attribute, such as type_name
, that exists in both types and then check against that. However, I prefer to avoid adding extra attributes solely for this purpose within this specific function.
Is there a more efficient way to approach this issue?