We are using now the @typescript-eslint
rule strict-boolean-expressions
with this config:
Now I am looking for the right way to check if a boolean is false or undefined.
For example I have this case:
const foo = (myBoolean?: boolean) => {
if (!myBoolean) console.log("myBoolean is false or undefined");
}
With the rule activated, I get this warning:
Unexpected nullable boolean value in conditional. Please handle the nullish case explicitly.
Should it be now:
if (myBoolean === undefined || !myBoolean)
Or is there a better practice?
Edit:
There is another case in React class components:
I have also another example with the state in a React class component:
interface IState {
myBoolean?: boolean;
}
type IProps = React.PropsWithChildren<unknown>;
export class TestComponent extends React.Component<IProps, IState> {
constructor(props: IProps) {
super(props);
this.state = { myBoolean: false };
}
public componentDidMount(): void {
if (!this.state.myBoolean) console.log("myBoolean", myBoolean);
}
public render(): JSX.Element {
return <MyComponent />;
}
}
I'd handle it by using a default value:
const foo = (myBoolean: boolean = false) => {
if (!myBoolean) {
console.log("myBoolean is false or [was] undefined");
}
};
In other situations where you can't or don't want to do that, if you want to use the rule, you could (as the warning said) use nullish coalescing:
const foo = (myBoolean?: boolean) => {
if (!(myBoolean ?? false)) {
console.log("myBoolean is false or undefined");
}
};