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

November 1, 2021 - 3 min read

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

TL;DR

// string literal union type with
// values of "admin", "owner", "user"
type Roles = "admin" | "owner" | "user";

// use the type "Roles" for the "role" variable
let role: Roles;

// assing a value other than "admin", "owner", "user"
role = "Hello World!"; // ❌ not allowed. Type '"Hello World!"' is not assignable to type 'Roles'

// assign a valid string value
role = "admin"; // ✅ allowed.

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

let role = "Hello World!";

As you can see from the above code that now we can have any string values assigned to the role variable. This is fine for now. But what if we need to restrict the values of the role variable to only hold certain string values like owner, admin, or user. To achieve this functionality in TypeScript, we can use string literal union types in TypeScript.

To do that first we can define a type called Roles and then assign string literal union type values of admin, owner, and user.

It can be done like this,

// string literal union type with
// values of "admin", "owner", "user"
type Roles = "admin" | "owner" | "user";

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

// string literal union type with
// values of "admin", "owner", "user"
type Roles = "admin" | "owner" | "user";

// use the type "Roles" for the "role" variable
let role: Roles;

Now let's try to assign a value other than the admin, owner or user string values to role variable like this,

// string literal union type with
// values of "admin", "owner", "user"
type Roles = "admin" | "owner" | "user";

// use the type "Roles" for the "role" variable
let role: Roles;

// assing a value other than "admin", "owner", "user"
role = "Hello World!"; // ❌ not allowed. Type '"Hello World!"' is not assignable to type 'Roles'

// assign a valid string value
role = "admin"; // ✅ allowed.

As you can see from the above code that the TypeScript compiler won't compile the code if the role variable doesn't have a valid string literal value and shows an error saying Type '"Hello World!"' is not assignable to type 'Roles' which is exactly what we want to happen.

Also assigning the value of admin is allowed since the admin string literal value is defined in the Roles type.

See the above code live in codesandbox.

That's all 😃!

Feel free to share if you found this useful 😃.