The string type is a primitive type that holds a text value.
In TypeScript, the string type is a type that can only hold text values (such as "Hello", 'World', or template strings).
let name: string = "Joyonto";
Here, the variable name can only accept string values.
With the string type, you can use text formatting, string methods (like length, toUpperCase(), etc.), and template literals.
Additionally, in TypeScript, you can define more specific and safer types using literal strings, union strings, and template literal types.
The two main ways to use the string type.
1. Declaring the type normally:
let city: string = "Dhaka";
2. Type inference (TypeScript automatically infers the type):
let country = "Bangladesh";
There are different ways to write strings.
Double Quotes:
let name: string = "Joyonto";
Single Quotes:
let message: string = 'Hello';
Backticks (Template Literals — Very Important)
`let name = "Joyonto";
let greeting = Hello, ${name}!
;`
- All JavaScript built-in string methods work with the string type in TypeScript:
let text: string = "Hello World";
text.length; // 11
text.toUpperCase(); // "HELLO WORLD"
text.toLowerCase(); // "hello world"
text.includes("Hello"); // true
text.split(" "); // ["Hello", "World"]
text.replace("World", "TypeScript"); // "Hello TypeScript"
- Literal Types in String:
In TypeScript, you can use literal value types with strings:
let status: "success" | "error" | "pending";
status = "success"; // valid
status = "loading"; // Error: "loading" is not assignable
- Union of String Types
type Role = "admin" | "user" | "guest";
let myRole: Role;
myRole = "admin"; // ✅
myRole = "manager"; // ❌
- String Enums
enum Direction {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT"
}
let dir: Direction = Direction.Left;
- String type parameter in a function
function greet(name: string): string {
return `Hello, ${name}!`;
}
greet("Joyonto"); // "Hello, Joyonto!"
- Optional, Default, and Nullable String
function printMessage(msg?: string) {
console.log(msg ?? "No message");
}
let username: string | null = null;
- Utility Types + String
type Person = { name: string; age: number };
type Keys = keyof Person; // "name" | "age"
- String Literal Types with Functions (Narrowing)
type NotificationType = "success" | "error";
function showNotification(type: NotificationType) {
if (type === "success") {
console.log("🎉 Success!");
} else {
console.log("❌ Error!");
}
}
Here, TypeScript uses type narrowing to understand that if the type is "success", then the other branch must be "error".
- as const with string literals:
const role = "admin" as const;
This creates an immutable string literal type, where role cannot be any other string.
- Type Guards for String
function logIfString(value: unknown) {
if (typeof value === "string") {
console.log(value.toUpperCase());
}
}
When the type is unknown, it is checked using typeof like this to handle the string.
- Utility Type — Record with string
type LangText = Record<string, string>;
const texts: LangText = {
title: "Hello",
description: "Here is the description",
};
With Record, you can create any key-value pair type where both the key and value are strings.
Some real-life examples:
type Gender = "male" | "female" | "other";
function handleGenderChange(g: Gender) {
// do something
}
type Status = "success" | "error";
function showToast(status: Status) {
if (status === "success") {
alert("Submitted successfully!");
}
}
Using TypeScript’s string type in a React.js project: Hello.tsx (a component that accepts string type props).
import React from "react";
type HelloProps = {
name: string;
};
const Hello: React.FC<HelloProps> = ({ name }) => {
return <h1>Hello, {name}!</h1>;
};
export default Hello;
App.tsx
import React from "react";
import Hello from "./Hello";
const App: React.FC = () => {
const userName: string = "Joyonto";
return (
<div>
<Hello name={userName} />
</div>
);
};
export default App;
Great