How to convert string to boolean in typescript Angular 4

后端 未结 5 814
后悔当初
后悔当初 2021-01-31 13:33

I know am not the first to ask this and as I mentioned in my title ,I am trying to convert string value boolean .

I have previously put some values into local storage,No

5条回答
  •  -上瘾入骨i
    2021-01-31 13:56

    Define extension: String+Extension.ts

    interface String {
      toBoolean(): boolean
    }
    
    String.prototype.toBoolean = function (): boolean {
      switch (this) {
        case 'true':
        case '1':
        case 'on':
        case 'yes':
          return true
        default:
          return false
      }
    }
    

    And import in any file where you want to use it '@/path/to/String+Extension'

提交回复
热议问题