Skip to content

变量: toBool

ts
const toBool: QueryConverter<boolean>;

定义于: url.ts:54

安全的 query 布尔转换器:'1' | 'true' | 'yes' | 'on'(忽略大小写与首尾空白)视为 true,其余一律 false

Param

value

query 中的原始字符串值

Returns

解析后的布尔值

备注

用来替代内置 Boolean——Boolean('false') === true(非空字符串一律为真)是常见坑。 作为 parseQuery 的 schema 转换器时,直接写内置 Boolean 会被自动替换成本函数,无需手动引入; 需要更严格/不同的判定时,也可传自定义函数如 v => v === 'true'。类型见 QueryConverter

示例

ts
toBool('true')  // => true
toBool('false') // => false(内置 Boolean('false') 却是 true)
toBool('ON')    // => true(忽略大小写)
toBool('0')     // => false

// 作为 schema 转换器
parseQuery('?a=false&b=1', { a: Boolean, b: Boolean }) // => { a: false, b: true }