enum Value {
First,
Second,
}
interface Data {
value: Value
number: number
}
interface SubData {
value: Value.Second
}
function calculation(input: SubData){
return;
}
function initiate(){
const input : Data = {
number: 100,
value: Value.Second
}
if(input.value !== Value.Second) return;
calculation(input)
// ^^^^ Types of property 'value' are incompatible.
// Type 'Value' is not assignable to type 'Value.Second'.
}
If
SubData
andData
had the same fields, we could use a type predicate to narrow it down. But my problem requires thatSubData
will only have a subset of the fields ofData
. Therefore a type predicate wouldn't work [playground].We could also change the type of
value
in the interfaceSubData
toValue
. And then move theif
check for the second value insidecalculation
function. But let's also say I don't want to do that. I don't want to give the function this responsibility.We could create a new object of type
SubData
based on the original object and then pass that tocalculation()
instead. But this feels like a workaround (and extra code) because we couldn't narrow down the type [playground].
Is there a way to properly narrow down the type without breaking the rules? (no any
or casting)