Function toStringSafe

  • Converts an input value to its string representation, that is not (null) and not (undefined). NOTE: If an exception occurrs, the default value is returned.

    Returns

    The input value as string.

    Example

    class TestClass {
    toString() { return 'Foo!'; }
    }

    class TestClass2 {
    toString() { throw new Error('An Error!'); }
    }

    const obj = {
    toString: () => '!!!BAZZZ!!!'
    }

    const obj2 = {
    toString() { throw new Error('An Error!'); }
    }

    toStringSafe(null) // ''
    toStringSafe(null, 'foo') // 'foo'
    toStringSafe(undefined) // ''
    toStringSafe(undefined, 'bar') // 'bar'
    toStringSafe(new TestClass2()) // ''
    toStringSafe(new TestClass2(), 'cat') // 'cat'
    toStringSafe(obj2) // ''
    toStringSafe(obj2, 'baz') // 'baz'

    toStringSafe(0) // '0'
    toStringSafe(0, 'baz') // '0'
    toStringSafe(false) // 'false'
    toStringSafe(false, 'fooBar') // 'false'
    toStringSafe('') // ''
    toStringSafe('', 'Barfoo') // ''
    toStringSafe(Symbol('TEST')) // 'Symbol(TEST)'
    toStringSafe(Symbol('TEST'), 'symbolDefault') // 'Symbol(TEST)'

    toStringSafe(new TestClass()) // 'Foo!'
    toStringSafe(new TestClass(), 'Bar!') // 'Foo!'

    toStringSafe(obj) // '!!!BAZZZ!!!'
    toStringSafe(obj, 'Barbara!') // '!!!BAZZZ!!!'

    Parameters

    • val: any

      The input value to check.

    • Optional defaultValue: string

      The custom default value.

    Returns string

Generated using TypeDoc