— TypeScript, Programming, Interfaces — 1 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.
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'.
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.
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'.
When you use the IOptions
interface, TypeScript will enforce the allowed values.
1function setOptions(options: IOptions) {2 // Implementation here3}4
5// Valid usage6setOptions({ size: 'medium' });7
8// Invalid usage, TypeScript will show an error9setOptions({ size: 'extra-large' });
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}
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.