typescript/strict-boolean-expressions Pedantic
Qué hace
Prohíbe certain types in boolean expressions.
¿Por qué es problemático?
Forbids usage of non-boolean types in expressions where a boolean is expected. boolean and never types are always allowed. Additional types which are considered safe in a boolean context can be configured via options.
The following nodes are checked:
- Arguments to the
!,&&, and||operators - The condition in a conditional expression (
cond ? x : y) - Conditions for
if,for,while, anddo-whilestatements.
Ejemplos
Ejemplos de código incorrecto para esta regla:
const str = "hello";
if (str) {
console.log("string");
}
const num = 42;
if (num) {
console.log("number");
}
const obj = { foo: "bar" };
if (obj) {
console.log("object");
}
declare const maybeString: string | undefined;
if (maybeString) {
console.log(maybeString);
}
const result = str && num;
const ternary = str ? "yes" : "no";Ejemplos de código correcto para esta regla:
const str = "hello";
if (str !== "") {
console.log("string");
}
const num = 42;
if (num !== 0) {
console.log("number");
}
const obj = { foo: "bar" };
if (obj !== null) {
console.log("object");
}
declare const maybeString: string | undefined;
if (maybeString !== undefined) {
console.log(maybeString);
}
const bool = true;
if (bool) {
console.log("boolean");
}Configuración
Esta regla acepta un objeto de configuración con las siguientes propiedades:
allowAny
tipo: boolean
predeterminado: false
Whether to allow any type in boolean contexts.
allowNullableBoolean
tipo: boolean
predeterminado: false
Whether to allow nullable boolean types (e.g., boolean | null) in boolean contexts.
allowNullableEnum
tipo: boolean
predeterminado: false
Whether to allow nullable enum types in boolean contexts.
allowNullableNumber
tipo: boolean
predeterminado: false
Whether to allow nullable number types (e.g., number | null) in boolean contexts.
allowNullableObject
tipo: boolean
predeterminado: true
Whether to allow nullable object types in boolean contexts.
allowNullableString
tipo: boolean
predeterminado: false
Whether to allow nullable string types (e.g., string | null) in boolean contexts.
allowNumber
tipo: boolean
predeterminado: true
Whether to allow number types in boolean contexts (checks for non-zero numbers).
allowString
tipo: boolean
predeterminado: true
Whether to allow string types in boolean contexts (checks for non-empty strings).
Cómo usarla
To enable this rule using the config file or in the CLI, you can use:
{
"options": {
"typeAware": true
},
"rules": {
"typescript/strict-boolean-expressions": "error"
}
}import { defineConfig } from "oxlint";
export default defineConfig({
options: { typeAware: true },
rules: {
"typescript/strict-boolean-expressions": "error",
},
});oxlint --type-aware --deny typescript/strict-boolean-expressionsVersión
Esta regla se añadió en v1.25.0.