String Literal Types in TypeScript: How to Define Types with Literal Values
TypeScript is an extension of JavaScript that adds support for static typing. One of its key features is the ability to define types. In this post, we will explore string literal types in TypeScript, which allow us to define types with literal values.
String literal types are a type of type literal in TypeScript. A type literal is a type that represents a value that is defined directly in the code, rather than being calculated or inferred at runtime.
In the case of string literal types, the value is a string literal. A string literal is a string that is defined using double or single quotes, for example:
const myString = "hello";
const myOtherString = 'world';
To define a string literal type, we use the syntax type MyStringLiteral = 'value';
, where MyStringLiteral
is the name of the type and value
is the string literal value. For example:
type MyStringLiteral = 'hello';
This defines a type called MyStringLiteral
that can only have the value 'hello'
.
We can also define a union of string literal types using the |
operator. For example:
type MyUnion = 'hello' | 'world';
This defines a type called MyUnion
that can have either the value 'hello'
or 'world'
.
Once we have defined a string literal type, we can use it to define the type of variables and function parameters. For example:
const myString: MyStringLiteral = 'hello';
function sayHello(name: MyStringLiteral) {
console.log(`Hello, ${name}!`);
}
In this example, we define a variable myString
with the type MyStringLiteral
and a function sayHello
with a parameter name
of type MyStringLiteral
.
We can also use string literal types to define the return type of functions. For example:
function getGreeting(name: MyStringLiteral): string {
return `Hello, ${name}!`;
}
In this example, we define a function getGreeting
that takes a parameter name
of type MyStringLiteral
and returns a string.
String literal types in TypeScript allow us to define types with literal values. We can use them to define the type of variables, function parameters, and return types. By using string literal types, we can make our code more expressive and easier to understand.