I want to create a Discriminated Union Type, where it isn't required to pass the discriminator value.
Here's my current code:
interface Single<T> {
multiple?: false // this is optional, because it should be the default
value: T
onValueChange: (value: T) => void
}
interface Multi<T> {
multiple: true
value: T[]
onValueChange: (value: T[]) => void
}
type Union<T> = Single<T> | Multi<T>
For testing I use this:
function typeIt<T>(data: Union<T>): Union<T> {
return data;
}
const a = typeIt({ // should be Single<string>
value: "foo",
onValueChange: (value) => undefined // why value is of type any?
})
const b = typeIt({ // should be Single<string>
multiple: false,
value: "foo",
onValueChange: (value) => undefined
})
const c = typeIt({ // should be Multi<string>
multiple: true,
value: ["foo"],
onValueChange: (value) => undefined
})
But I get a bunch of errors and warnings...:
In
const a
'sonValueChange
the type of the parametervalue
isany
. When settingmultiple: false
explicitly (like inconst b
) it gets correctly inferred asstring
.const c
doesn't work at all. I get this error: "Type 'string' is not assignable to type 'string[]'".
Do you have any idea how to solve this?
I've created a TypeScript Playground with this code