javascriptnode.jstypescripttypescript-genericstype-fest

Can't use type-fest GreaterThan as parameter type


I tried using type-fest GreaterThan type for the function parameter and got an error

when I write the following function:

import type {GreaterThan} from 'type-fest'

function printNumberOfBooks <N extends number> (numberOfBooks: GreaterThan<N, 0>): void {
    console.log(numberOfBooks)
}

and... :

printNumberOfBooks(2)

I get the following typescript error:

Argument of type 'number' is not assignable to parameter of type 'never'

It took me hours... I didn't find a solution

Official documentation of type-fest GreaterThan type

Official documentation of typescript Generics


Solution

  • Check this out ...

    In above link as n0tKamui said:

    GreaterThan is a boolean reduction, so you would need to check it

    Base on this and other things like the friendly error message... The best way to implement it is: (shout-out to nadameu)

    import type { GreaterThan } from 'type-fest';
    
    function printNumberOfBooks<N extends number>(
      numberOfBooks: GreaterThan<N, 0> extends true
        ? N
        : { error: 'input is not greater than zero' }
    ): void {
      console.log(numberOfBooks);
    }
    
    printNumberOfBooks(2); // No error
    
    printNumberOfBooks(-3);
    //                 ^       Argument of type 'number' is not assignable to
    //                         parameter of type '{ error: "input is not greater 
    //                         than zero"; }'.ts(2345)