I have a function which should be able to receive two similar types as argument. Depending on if props.multi is true or false.
The problem is that it still allows me to pass value = [] with multi = false. How can I get rid of this?
interface PropsSingle<T> {
value: T,
multi: false
}
interface PropsMulti<T> {
value: T[],
multi: true
}
function foo<T>(props: PropsSingle<T> | PropsMulti<T>) {
if(props.multi) {
let arr = props.value // type detection works fine
} else {
let obj = props.value // type detection works fine
}
}
foo({multi: true, value: []}) // works as expected
foo({multi: true, value: {}}) // throws error as expected
foo({multi: false, value: {}}) // works as expected
foo({multi: false, value: []}) // THIS SHOULD THROW AN ERROR
I already have tried foo<T extends object>(...) and foo<T extends {[key: string]: any}>(...)
The only kinda solution / workaround I found is this:
interface PropsSingle<T> {
value: T extends any[] ? never : T,
multi: false
}
But that looks weird to me.
Why can't I restrict the type at function foo?