Home > Back-end >  How do I accept numbers that are only multiples of 5 in TypeScript?
How do I accept numbers that are only multiples of 5 in TypeScript?

Time:01-09

Not sure if this is possible, but was curious, hence the question. I was building a component that houses an square image which takes in a size prop. I would like to enforce that the size is always a multiple of 5 so the image remains crisp.

My meager knowledge on the topic led me to this, but doesn't really work the way I expected it to.

type Props = {
  size: (x) => (x % 5 === 0)
};

At the end of the day, I just want to be able to type check my props as I'm using them. For example:

// TS should throw an error
<Logo size={32} />

// TS should allow it
<Logo size={40} />

Is something like this possible with TypeScript?

CodePudding user response:

Very very interesting question and TS shines here :)) Starting from 4.1 you can have this example.

Since all multipliers of 5 end with either zero or five you can solve it like this

type EndsWithZeroOrFive = '0' | '5'
type OtherDigits = `${number}` | ''
type MultiplierOfFive = `${OtherDigits}${EndsWithZeroOrFive}`

const n1 : MultiplierOfFive = '10' 
const n2 : MultiplierOfFive = '25' 
// no issue

const n3 : MultiplierOfFive = '12' 
// Type '"12"' is not assignable to type 'EndsWithZeroOrFive | `${number}0` | `${number}5`'.
  •  Tags:  
  • Related