I have a function that takes in parameters with similar structure and uses type guards internally to determine the type of parameter being passed.
type Example1 = {
data: 'data',
param1: 'yes'
}
type Example2 = {
data: 'data',
param2: true
}
type Example = Example1 | Example2;
export const sampleFunction = (sample: Example): Example => {
const isExample1 = (unknownSample: Example): unknownSample is Example1 => {
return (unknownSample as Example1).param1 === undefined ? false : true;
}
const execute = (): Example => {
if (isExample1(sample)) {
return sample;
}
return sample;
}
return execute()
}
In my real application, a more complex object of a different type is returned, but for simplicity purposes in this example, I am returning the same object.
When I run the function
const ex1: Example1 = {
data: 'data',
param1: 'yes'
}
const result = sampleFunction(ex1);
In my IDE, TypeScript correctly recognizes that example
in the following block
if (isExample1(sample)) {
return sample;
}
has the correct type
(parameter) sample: Example1
You can see that the object assigned to sample
is then returned from the function and in this case assigned to result
.
However, despite understanding the correct type within the return blocks, TypeScript does not assign result
as type Example1
and instead assigns it the broader type Example
.
const result = sampleFunction(ex1);
This causes an error when trying to access
result.param1
Property 'param1' does not exist on type 'Example'.
Do type guards only apply within the current execution block or am I misunderstanding their purpose?