Skip to content
DeveloperMemos

Enforcing Specific String Values in TypeScript Interfaces

TypeScript, Programming, Interfaces1 min read

TypeScript, a statically typed superset of JavaScript, provides powerful ways to define and enforce the structure of objects. One common requirement is to restrict an interface property to a specific set of string values. This article explains how to accomplish this in TypeScript, ensuring that objects conform to a predefined set of string values.

The Challenge

In TypeScript, you might encounter situations where an object's property should only accept specific string values. For instance, you're creating an interface for a configuration object where a property should only accept predefined string literals like 'small', 'medium', or 'large'.

The Solution: String Literal Types

TypeScript's string literal types are the perfect solution for this challenge. They allow you to specify that a string can only be a specific set of string values.

Step 1: Defining the Interface

You start by defining an interface with a property that uses string literal types.

1interface IOptions {
2 size: 'small' | 'medium' | 'large';
3}

In this example, the size property can only be 'small', 'medium', or 'large'.

Step 2: Using the Interface

When you use the IOptions interface, TypeScript will enforce the allowed values.

1function setOptions(options: IOptions) {
2 // Implementation here
3}
4
5// Valid usage
6setOptions({ size: 'medium' });
7
8// Invalid usage, TypeScript will show an error
9setOptions({ size: 'extra-large' });

Step 3: Expanding the Interface

If you need to add more properties to your interface, you can do so while still enforcing specific string values for each.

1interface IOptions {
2 size: 'small' | 'medium' | 'large';
3 color: 'red' | 'green' | 'blue';
4}

Advanced Use: Type Aliases

For cleaner code, especially when you have repeated string literals, use type aliases.

1type Size = 'small' | 'medium' | 'large';
2type Color = 'red' | 'green' | 'blue';
3
4interface IOptions {
5 size: Size;
6 color: Color;
7}

Using type aliases makes your code more maintainable and readable.