Today, I encountered a bug that I believe should have been caught by the type system. Let me illustrate with an example:
function getModel(): Model { /* ... */ }
function processModelName(name: string) {
return name.replace('x', 'y') // recently added code
}
const model = getModel();
processModelName(model?.name);
The code above does not produce any TypeScript errors.
However, even though it is not declared, getModel
could potentially return undefined
. The function getModel
is an external dependency, so changing its return type to undefined|Model
is not possible. Even when hovering over the model variable, it appears to be of type Model.
Why is this type information getting lost? I expected that using optional chaining with processModelName
would raise an error, as the function only accepts strings and we are dealing with a potential nullish case here.
How can this be configured in tsconfig.json?