Borislav Hadzhiev
Sat Mar 05 2022·2 min read
Photo by Abigail Keenan
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.
// ✅ 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.
// ⛔️ 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.
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.
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.
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.
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.