Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ts: why Argument of type 'number' is not assignable to parameter of type 'never'

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading