Given the following example:
type Dictionary = {
[key: string] : string | undefined
}
function greet(name: string) {
return 'Hello ' + name + '!';
}
function callGreetError(key: string, d: Dictionary) {
if (typeof d[key] !== 'undefined') {
return greet(d[key]) // TS Error: Argument of type 'string | undefined' is not assignable to parameter of type 'string'.Type 'undefined' is not assignable to type 'string'.(2345)
}
return key + ' is not in dictionary';
}
function callGreetNoError(key: string, d: Dictionary) {
const storedVal = d[key];
if (typeof storedVal !== 'undefined') {
return greet(storedVal) // Error goes away when value is stored in an external var.
}
return key + ' is not in dictionary';
}
I'm trying to understand why on callGreetError
the type of d[key]
inside the if
block isn't inferred to be a string
even though I'm explicitly telling TS it isn't undefined
.
And why storing the value of d[key]
on an external var storedVal
on callGreetNoError
fixes this error.