Home > Net >  How to restrict property type to be percentage?
How to restrict property type to be percentage?

Time:12-17

I want to set a type of variable that can only receive percentage values. for example:

let value: string | number.

If the user passes a string to this variable value, the typescript can only receive with this pattern

value= "30%"

If the user passes

value= "foo"

the typescript should show an error.

CodePudding user response:

You should be able to use template literal types:

type Percentage = `${number}%` | number
  • Related