Allow only specific string values with TypeScript type

avatar

Borislav Hadzhiev

Sat Mar 05 20222 min read

Allow only specific string values with TypeScript type #

Use a string literal type to only allow specific string values using a TypeScript type, e.g. const str: 'draft' | 'sent' = 'draft';. String literals allow us to refer to specific strings in type positions. If the specified string is not in the literal type, an error is thrown.

index.ts
// ✅ with interface interface Person { name: 'Alice' | 'Bob' | 'Carl'; } const p: Person = { name: 'Alice', }; // ✅ with Type Alias type Sizes = 'small' | 'medium' | 'large'; const s: Sizes = 'small'; // ✅ inline const str: 'draft' | 'sent' = 'draft'; // ✅ for function parameters function logMessage(message: 'hello world' | 'howdy world') { console.log(message); } logMessage('hello world');

The examples show how to use a string literal type to only allow assignment to specific string values.

String literal types allow us to refer to specific strings in type positions.

Assignment of a string that is not a member of the literal type, causes an error.

index.ts
// ⛔️ Type '"hello"' is not assignable to // type '"draft" | "sent"'.ts(2322) const str: 'draft' | 'sent' = 'hello';

An easy way to think about string literal types is - they are a union type with specific string values instead of types.

Literal types can also be used for numbers and booleans. For example, the type boolean is just an alias for the union true | false.

Alternatively, you could use an enum.

Use an enum to only allow specific string values using a TypeScript type, e.g. const emailStatus: EmailStatus = EmailStatus.Read;. Enums allow us to define a set of named constants. If the specified string is not a member of the enum, an error is thrown.

index.ts
enum EmailStatus { Read = 'READ', Unread = 'UNREAD', Draft = 'DRAFT', } // ✅ using interfaces interface JobEmails { status: EmailStatus; } const obj: JobEmails = { status: EmailStatus.Read, }; // ✅ inline assignment const emailStatus: EmailStatus = EmailStatus.Read;

Enums are sometimes easier to read than string literal types.

Note that enums are real objects and exist at runtime. You can use dot notation to access a property on an enum.

The emailStatus variable in the example can only have one of the 3 values that are present in the EmailStatus enum.

An assignment of a different string, would cause the type checker to throw an error.

index.ts
enum EmailStatus { Read = 'READ', Unread = 'UNREAD', Draft = 'DRAFT', } // ⛔️ Error: Type '"hello"' is not // assignable to type 'EmailStatus'.ts(2322) const emailStatus: EmailStatus = 'hello';

The main advantage of using enums over string literal types is - they make your code easier to read and organize.

The whole purpose of enums is defining a group of named and related constants.

Use the search field on my Home Page to filter through my more than 1,000 articles.