Open In App

How to Require a Specific String in TypeScript Interface ?

Last Updated : 09 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

To require a specific string in the TypeScript interface, we have different approaches. In this article, we are going to learn how to require a specific string in the TypeScript interface.

Below are the approaches used to require a specific string in the TypeScript interface:

Approach 1: Using String Literal Type

This approach utilizes string literal types in TypeScript interfaces to define a property with specific allowed string values. In the below example,

  1. Interface Definition (TaskStatus):
    • The TaskStatus interface is defined with a property named status.
    • The status property is restricted to having one of three specific string values: “todo”, “in-progress”, or “done” using string literal types.
  2. Valid Object (task1):
    • An object task1 is created with the status property set to a valid value, “todo”.
    • The TypeScript compiler allows this object because “todo” is one of the specified string values in the interface.

Example: Here, the TaskStatus interface restricts the status property to the string values “todo”, “in-progress”, or “done”.

Javascript




// Using String Literal Type
interface TaskStatus {
    status: "todo" | "in-progress" | "done";
}
 
// Valid object
const task1: TaskStatus = { status: "todo" };
console.log(task1.status); // Output: "todo"


Output:

todo

Approach 2: Using Enum

Enums provide a way to define a set of named constant values. In this approach, an enum is used to create a set of allowed string values for a property in an interface. In the below example,

  1. Enum Definition (Weekday):
    • An enum named Weekday is defined, where each enum member is assigned a specific string value representing days of the week.
  2. Interface Definition (Schedule):
    • The Schedule interface is defined with a property named day.
    • The day property is restricted to having one of the enum values from Weekday.
  3. Valid Object (meeting):
    • An object meeting is created with the day property set to a valid enum value, Weekday.Wednesday.
    • The TypeScript compiler allows this object because Wednesday is a valid enum value.

Example: Here, the Weekday enum is used to restrict the day property in the Schedule interface to specific string values.

Javascript




// Using Enum
enum Weekday {
    Monday = "Monday",
    Tuesday = "Tuesday",
    Wednesday = "Wednesday",
    Thursday = "Thursday",
    Friday = "Friday",
}
 
interface Schedule {
    day: Weekday;
}
 
// Valid object
const meeting: Schedule = { day: Weekday.Wednesday };
console.log(meeting.day); // Output: "Wednesday"


Output:

Wednesday


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads