-
Notifications
You must be signed in to change notification settings - Fork 13.3k
Closed
Closed
Copy link
Labels
Working as IntendedThe behavior described is the intended behavior; this is not a bugThe behavior described is the intended behavior; this is not a bug
Description
First of all thank you for sharing awesome technology with community ❤️
TypeScript Version: 3.8.3
Search Terms:
Object is possibly null, incorrectly possibly null, truthy check, 2531 ...
Code
Simplified example
type MyType = {
prop: any;
} | null;
function myMethod(arg: MyType) {
return arg && (arg as MyType).prop;
}Project real case
export interface Message {
translationKey: string;
values?: any[] | { [key: string]: any };
}
type MessagesTree = {
[key: string]: Message | Message[] | MessagesTree | null;
} | null;
const castArray = (val:any) => (Array.isArray(val) ? val : [val]);
function myMethod(messages: MessagesTree = {}) {
return castArray(messages).filter(
(msg: Message | MessagesTree) =>
msg && (msg.translationKey || (msg as MessagesTree).explicit));
// ^ truthy check ^ Object is possibly 'null'. ts(2531)
}Expected behavior:
it is not possible to get there null as it is after truthy check, therefore I would expct not to get error about possible null
Actual behavior:
it raises possible null error
I need to force non-null by "!" ---> (msg as MessagesTree)!.explicit to avoid error
Related Issues: Did you find other bugs that looked similar? No, all I found had differences and therefore their explanations/solutions did not match my case.
Thank you! 🙏
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
Working as IntendedThe behavior described is the intended behavior; this is not a bugThe behavior described is the intended behavior; this is not a bug