Skip to content

toBoolean()

此函数属于 Iconify Utils 包

函数 toBoolean() 将字符串转换为布尔值。它用于解析各种可能的组件属性值,以便在 IconCustomisations 属性中使用它们。

用法

该函数包含以下参数:

  • namestring。属性名称。
  • valueunknown。要解析的值。
  • defaultValueboolean。当 value 无法解析时返回的值。

函数返回 boolean 值。

示例

demo.ts
tsimport { toBoolean } from '@iconify/utils';

/**
* Using React or Svelte syntax for attributes for demo
*
* For default value using the opposite of expected value to make sure that value has been parsed
*/


// Returns true
console.log(`Testing hFlip={true}:`, toBoolean('hFlip', true, false));
console.log(`Testing hFlip="true":`, toBoolean('hFlip', 'true', false));
console.log(`Testing hFlip="hFlip":`, toBoolean('hFlip', 'hFlip', false));
console.log(`Testing hFlip={1}:`, toBoolean('hFlip', 1, false));

// Returns false
console.log(`Testing hFlip={false}:`, toBoolean('hFlip', false, true));
console.log(`Testing hFlip={0}:`, toBoolean('hFlip', 0, true));
console.log(`Testing hFlip="false":`, toBoolean('hFlip', 'false', true));
console.log(`Testing hFlip="":`, toBoolean('hFlip', '', true));
Result:
Testing hFlip={true}: true
Testing hFlip="true": true
Testing hFlip="hFlip": true
Testing hFlip={1}: true
Testing hFlip={false}: false
Testing hFlip={0}: false
Testing hFlip="false": false
Testing hFlip="": false