How to Require a Specific String in TypeScript Interface ?
Last Updated :
09 Jan, 2024
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,
- 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.
- 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
interface TaskStatus {
status: "todo" | "in-progress" | "done" ;
}
const task1: TaskStatus = { status: "todo" };
console.log(task1.status);
|
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,
- Enum Definition (
Weekday
):
- An enum named
Weekday
is defined, where each enum member is assigned a specific string value representing days of the week.
- 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
.
- 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
enum Weekday {
Monday = "Monday" ,
Tuesday = "Tuesday" ,
Wednesday = "Wednesday" ,
Thursday = "Thursday" ,
Friday = "Friday" ,
}
interface Schedule {
day: Weekday;
}
const meeting: Schedule = { day: Weekday.Wednesday };
console.log(meeting.day);
|
Output:
Wednesday
Share your thoughts in the comments
Please Login to comment...