Typescript 如何使用严格的布尔表达式检查false或undefined?

Typescript 如何使用严格的布尔表达式检查false或undefined?,typescript,typescript-eslint,Typescript,Typescript Eslint,我们现在将@typescript eslint规则严格布尔表达式用于此配置: 现在,我正在寻找正确的方法来检查布尔值是否为false或未定义 例如,我有一个案例: const foo = (myBoolean?: boolean) => { if (!myBoolean) console.log("myBoolean is false or undefined"); } 规则激活后,我收到以下警告: 条件中出现意外的可为null的布尔值。请明确处理空值情况。 现在

我们现在将
@typescript eslint
规则
严格布尔表达式
用于此配置:

现在,我正在寻找正确的方法来检查布尔值是否为false或未定义

例如,我有一个案例:

const foo = (myBoolean?: boolean) => {
  if (!myBoolean) console.log("myBoolean is false or undefined");
}
规则激活后,我收到以下警告:
条件中出现意外的可为null的布尔值。请明确处理空值情况。

现在应该是:

if(myBoolean==未定义的| |!myBoolean)

还是有更好的做法

编辑:

React类组件中还有另一种情况:

我还有另一个关于React类组件中状态的示例:

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 />;
    }
}
interface-IState{
myBoolean?:布尔型;
}
IProps类型=React.PropsWithChildren;
导出类TestComponent扩展了React.Component{
建造师(道具:IProps){
超级(道具);
this.state={myBoolean:false};
}
公共组件didmount():void{
if(!this.state.myBoolean)console.log(“myBoolean”,myBoolean);
}
public render():JSX.Element{
返回;
}
}

我会使用默认值来处理它:

constfoo=(myBoolean:boolean=false)=>{
if(!myBoolean){
log(“myBoolean为false或[was]未定义”);
}
};
在不能或不想这样做的其他情况下,如果要使用该规则,可以(如警告所述)使用nullish合并:

constfoo=(myBoolean?:boolean)=>{
如果(!(myBoolean??false)){
log(“myBoolean为false或未定义”);
}
};

我会使用默认值来处理它:

constfoo=(myBoolean:boolean=false)=>{
if(!myBoolean){
log(“myBoolean为false或[was]未定义”);
}
};
在不能或不想这样做的其他情况下,如果要使用该规则,可以(如警告所述)使用nullish合并:

constfoo=(myBoolean?:boolean)=>{
如果(!(myBoolean??false)){
log(“myBoolean为false或未定义”);
}
};

我想知道,如何将
null
传递到函数中?(V3.5.1,但它在最新版本中也不允许这种情况发生)@MikeS不能,但可以省去参数或传递
undefined
。“null ish”中的“ish”是因为如果左侧值为
null
未定义
:-),则
取右侧值问题是关于
false
undefined
。还是我误解了你的观点?这是一种很酷的方式!别想了。这解决了我的问题。第一种方法对我的功能来说很酷。第二种方法非常好,例如React类组件中的状态布尔。我也有这个箱子!谢谢:)@Tommy-只是FWIW,在状态示例中,我会用
false
初始化它,因此类型是
boolean
,而不是
boolean |未定义的
@Tommy-不要在接口中选择我的
myBoolean
。只是
myBoolean:boolean
。我想知道如何将
null
传递到函数中?(V3.5.1,但它在最新版本中也不允许这种情况发生)@MikeS不能,但可以省去参数或传递
undefined
。“null ish”中的“ish”是因为如果左侧值为
null
未定义
:-),则
取右侧值问题是关于
false
undefined
。还是我误解了你的观点?这是一种很酷的方式!别想了。这解决了我的问题。第一种方法对我的功能来说很酷。第二种方法非常好,例如React类组件中的状态布尔。我也有这个箱子!谢谢:)@Tommy-只是FWIW,在状态示例中,我会用
false
初始化它,因此类型是
boolean
,而不是
boolean |未定义的
@Tommy-不要在接口中选择我的
myBoolean
。只是
myBoolean:boolean