When dealing with a type that can have two formats based on the value of one of its keys, such as:
type singleOrMultiValue = {isSingle: true, value: string} | {isSingle: false, set: Array<string>}
I have found it useful in preventing errors like
const val : singleOrMultipleValue = {isSingle: false, value: '1'}
.
However, when trying to determine the type of a variable at runtime, I came across an issue:
if (val.isSingle) {
console.log(val.value)
} else {
console.log(val.set[0])
}
This resulted in an error stating that value
does not exist on type singleOrMultiValue
for {isSingle: false}
. Is there a way to specify within this if scope that isSingle
has a value of true? Or do I need to explicitly declare another variable or use as any
?
Any insights would be greatly appreciated!