create a type that only has even numbers in typescript

To create a type in TypeScript that only accepts even numbers, you can use the number type with a union of even numbers. Here is an example:

index.ts
type EvenNumber = 0 | 2 | 4 | 6 | 8;

const myNumber: EvenNumber = 4; // this is valid
const myOtherNumber: EvenNumber = 3; // this will give a type error
155 chars
5 lines

In the above example, we created a type called EvenNumber that only accepts the numbers 0, 2, 4, 6, and 8. Any other even number will not be assignable to this type and will result in a type error.

You can extend this to include larger even numbers as needed.

gistlibby LogSnag