Reputation: 467
const localAuth = async (callback: () => any) => {
// not sure the return type of callback, so cast a any type
const ok = Math.random()
if (ok > 0.5)
return callback()
else {
return null
}}
localAuth(() => null).then(val => {
console.log(val.mayNotExist) // doesn't complain, but val maybe null!
})
The typescript code is as above, because the return type of callback is not sure, so I assigned it a any type, but apparently any type swallows the 'null path', how to change the code to not miss the null possibility?
Upvotes: 5
Views: 2886
Reputation: 1040
Explicitly define the return type of your localAuth function to be a union of your callback type and null.
type anyFunction = () => any;
const localAuth = async (callback: anyFunction): Promise<null|anyFunction> => {
const ok = Math.random()
if (ok > 0.5)
return callback()
else {
return null;
}
};
localAuth(() => null).then(val => {
console.log(val.arguments) // complains because val may be null
if (val) {
console.log(val.arguments) // doesn't complain, because you've checked
}
});
This way, you will get the Object is possibly 'null'
issue from the typescript compiler for your val.mayNotExist
example, as expected.
Typescript playground link so you can see it in action
Edit 1:
To answer your comment, you can use type aliases.
const localAuth = async <T>(callback: () => T): Promise<null | T> => {
const ok = Math.random()
if (ok > 0.5)
return callback()
else {
return null;
}
};
localAuth(() => null).then(val => {
// val is type null
});
localAuth(() => '').then(val => {
// val is type (string | null)
});
Live typescript playground example
Upvotes: 1