How to allow only certain number values for variables or constants in TypeScript?

November 2, 2021 - 3 min read

To allow only certain number values for variables or constants, we can use a number literal union type in TypeScript.

TL;DR

// number literal union type with
// values of "0", "1", "2"
type PriorityNumbers = "0" | "1" | "2";

// use the type "PriorityNumbers" for the "priority" variable
let priority: PriorityNumbers;

// assing a value other than "0", "1", "2"
priority = 200; // ❌ not allowed. Type '200' is not assignable to type 'PriorityNumbers'

// assign a valid number value
priority = "0"; // ✅ allowed.

For example, let's say we have a variable called priority like this,

let priority = 200;

As you can see from the above code that now we can have any number values assigned to the priority variable. This is fine for now. But what if we need to restrict the values of the priority variable to only hold certain number values like 0, 1, or 2 (Think the concept of priority in terms of numbers in which lower the number higher the priority is). To achieve this functionality in TypeScript, we can use number literal union types in TypeScript.

To do that first we can define a type called PriorityNumbers and then assign number literal union type values of 0, 1, and 2.

It can be done like this,

// number literal union type with
// values of "0", "1", "2"
type PriorityNumbers = "0" | "1" | "2";

Now let's use the PriorityNumbers type for the priority variable. It can be done like this,

// number literal union type with
// values of "0", "1", "2"
type PriorityNumbers = "0" | "1" | "2";

// use the type "PriorityNumbers" for the "priority" variable
let priority: PriorityNumbers;

Now let's try to assign a value other than the 0, 1 or 2 number values to priority variable like this,

// number literal union type with
// values of "0", "1", "2"
type PriorityNumbers = "0" | "1" | "2";

// use the type "PriorityNumbers" for the "priority" variable
let priority: PriorityNumbers;

// assing a value other than "0", "1", "2"
priority = 200; // ❌ not allowed. Type '200' is not assignable to type 'PriorityNumbers'

// assign a valid number value
priority = "0"; // ✅ allowed.

As you can see from the above code that the TypeScript compiler won't compile the code if the priority variable doesn't have a valid number literal value and shows an error saying Type '200' is not assignable to type 'PriorityNumbers' which is exactly what we want to happen.

Also assigning the value of 0 is allowed since the 0 number literal value is defined in the PriorityNumbers type.

See the above code live in codesandbox.

That's all 😃!

Feel free to share if you found this useful 😃.