Steps to reproduce:
- I define a function that returns a promise of string or false.
- I call and return an async function and return a string or false from the catch method.
Problem:
Typescript claims it doesn’t match the type definition because true
is not assignable to the type string|false
.
Question:
Since there is no explicit true
anywhere, why does typescript infer this value and complain?
Further thoughts:
When returning false as false
from the async function’s catch
method, this makes the error go away. Why? Typescript doesn’t know that false is false? It is not necessary to write as false
in the then()
method, only the catch()
, why?
Code example:
const log = (...data:(
|string
|Error
)[]):Promise<string|false> => {
return fetch('/logs', {
method: 'POST',
body: 'minimal reproducible example',
})
.then(r=>{
if(!r.ok){
return false
}else{
return 'stuff and things'
}
})
.catch(e=>{
return false // `as false` resolves the warning.
})
.finally(()=>{
console.log('ok')
})
}
Error message:
Type ‘Promise<boolean | “stuff and things”>’ is not assignable to type ‘Promise<string | false>’.
Type ‘boolean | “stuff and things”‘ is not assignable to type ‘string | false’.
Type ‘true’ is not assignable to type ‘string | false’.(2322)
No quick fixes available
Additional experiment:
A non async catch returning false does not have this problem:
// No warnings:
const log = (...data:(
|string
|Error
)[]):string|false => {
try{
if(Math.random()>.5){
throw 'Error'
}
return 'stuff'
}catch(e){
return false
}
}