Type for non-falsy, aka truthy

后端 未结 2 2023
余生分开走
余生分开走 2021-01-17 08:33

In TypeScript, is there a type for truthy?

I have this method: Object.keys(lck.lockholders).length; enqueue(k: any, obj?: any): void think with TS there is a

2条回答
  •  时光说笑
    2021-01-17 08:56

    There is no Truthy type, BUT you can leverage type guard system (type predicate) to help TypeScript to understand what really is truthy and assign it truthy type!

    Let's define Falsy type and generic isTruthy function:

    type Falsy = false | 0 | '' | null | undefined;
    
    // this is a type predicate - if x is `truthy`, then it's T
    const isTruthy = (x: T | Falsy): x is T => !!x;
    
    

    Now we can use out isTruthy function to find truthy values and TypeScript will correctly assign the "truthy" type to the result.

    Examples:

    {   // removing boolean "false" type
      const result: string | false = Math.random() > 0.5 ? 'a' : false;
      const truthyResult: string = isTruthy(result) ? result : 'was false';
    }
    {   // filtering only numbers from array
      const result: (number | undefined)[] = [42, undefined, 8, 16];
      const truthyResult: number[] = result.filter(isTruthy);
    }
    {   // filtering only Promises from array
      const result: (Promise | null)[] = [Promise.resolve('a'), null, Promise.resolve('b'), Promise.resolve('c')];
      const truthyResult: Promise[] = result.filter(isTruthy);
    }
    
    

提交回复
热议问题