type AssertPositive<N extends number> =
number extends N ?
N :
`${N}` extends `-${string}` ? never : N;
class Millseconds<N extends number> {
constructor(public readonly value: AssertPositive<N>){
if(this.value < 0){
throw new Error('Value Cannot Smaller Than 0');
}
}
}
new Millseconds(1); // OK
// Argument of type 'number' is not assignable to parameter of type 'never'.(2345)
new Millseconds(-1); // Error
new Millsecond(-1) why -1 parameter of type "never"?
type of parameter-1 , Why no access to condition 1
number extends N ? N : `${N}` extends `-${string}` ? never : N
conditon1 : N
condition2: `${N}` extends `-${string}` ? never : N
I want to know what causes
>Solution :
Looking at the type (reformatted for clarity):
type AssertPositive<N extends number> =
number extends N
? N
: `${N}` extends `-${string}`
? never
: N;
If we take -1 as the value for N, then the condition number extends -1 evaluates to false, thus prompting the evaluation of the second condition.
The extends clause is defined in terms of generalization and specialization: specific extends general evaluates to true, while general extends specific evaluates to false.
The inverse condition, i.e. -1 extends number, would evaluate to true.