The string type in TypeScript.
joyonto kumar roy

joyonto kumar roy @joyontokumar

About: Front End Engineer

Location:
Bangladesh
Joined:
Jun 24, 2019

The string type in TypeScript.

Publish Date: Jun 28
1 1

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"
Enter fullscreen mode Exit fullscreen mode

- 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
Enter fullscreen mode Exit fullscreen mode

- Union of String Types

type Role = "admin" | "user" | "guest";

let myRole: Role;

myRole = "admin";  // ✅
myRole = "manager"; // ❌
Enter fullscreen mode Exit fullscreen mode

- String Enums

enum Direction {
  Up = "UP",
  Down = "DOWN",
  Left = "LEFT",
  Right = "RIGHT"
}

let dir: Direction = Direction.Left;
Enter fullscreen mode Exit fullscreen mode

- String type parameter in a function

function greet(name: string): string {
  return `Hello, ${name}!`;
}

greet("Joyonto"); // "Hello, Joyonto!"
Enter fullscreen mode Exit fullscreen mode

- Optional, Default, and Nullable String

function printMessage(msg?: string) {
  console.log(msg ?? "No message");
}

let username: string | null = null;
Enter fullscreen mode Exit fullscreen mode

- Utility Types + String

type Person = { name: string; age: number };
type Keys = keyof Person; // "name" | "age"
Enter fullscreen mode Exit fullscreen mode

- String Literal Types with Functions (Narrowing)

type NotificationType = "success" | "error";

function showNotification(type: NotificationType) {
  if (type === "success") {
    console.log("🎉 Success!");
  } else {
    console.log("❌ Error!");
  }
}
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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());
  }
}
Enter fullscreen mode Exit fullscreen mode

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",
};
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode
type Status = "success" | "error";

function showToast(status: Status) {
  if (status === "success") {
    alert("Submitted successfully!");
  }
}
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

Comments 1 total

Add comment