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:
Table of Content
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 namedstatus
. -
The
status
property is restricted to having one of three specific string values: “todo”, “in-progress”, or “done” using string literal types.
-
The
-
Valid Object (
task1
):-
An object
task1
is created with thestatus
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.
-
An object
Example: Here, the TaskStatus
interface restricts the status
property to the string values “todo”, “in-progress”, or “done”.
// 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,
-
Enum Definition (
Weekday
):-
An enum named
Weekday
is defined, where each enum member is assigned a specific string value representing days of the week.
-
An enum named
-
Interface Definition (
Schedule
):-
The
Schedule
interface is defined with a property namedday
. -
The
day
property is restricted to having one of the enum values fromWeekday
.
-
The
-
Valid Object (
meeting
):-
An object
meeting
is created with theday
property set to a valid enum value,Weekday.Wednesday
. -
The TypeScript compiler allows this object because
Wednesday
is a valid enum value.
-
An object
Example: Here, the Weekday
enum is used to restrict the day
property in the Schedule
interface to specific string values.
// 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