I have below code in TypeScript. The function isDataAvailable returns true if data is not undefined. In updateData function, it has a if condition on the isDataAvailable return value but the compiler reports an error on data.i++: 'data' is possibly 'undefined'..
If the data has been checked in isDataAvailable function already, why does TypeScript still think it could be undefined? Is there a way to make it check the previous function return value?
let data: { i: number; j: number } | undefined = undefined;
const isDataAvailable = () => {
return !!data;
};
const updateData = () => {
if (isDataAvailable()) {
data.i++;
}
};
>Solution :
I think you’re looking for type predicates
They don’t deal with globals, though, they need to be arguments to the function:
type Data = { i: number; j: number }
const isDataAvailable = (data?: Data): data is Data => {
return !!data;
};
const updateData = (data?: Data) => {
if (isDataAvailable(data)) {
data.i++;
}
};
This is kind of a contrived example, because the above could be represented just by doing:
const updateData = (data?: Data) => {
if (data) {
data.i++;
}
};
But hopefully type predicates is what you were looking for!