← Back to list

Working with string in TypeScript

Strings are one of the most commonly used data types in any programming language, and TypeScript is no exception. Whether you’re handling…

Rıdvan Demirci · 2025-05-27 16:54 · 0 claps · 3.7 min read
#typescript #string #string-type #template-literals #template-literal-types
Open on Medium ↗
Wiki topics: GEN · Genomics & Sequencing 💻 · Programming 🌐 · Web Development

Working with string in TypeScript

Strings are one of the most commonly used data types in any programming language, and TypeScript is no exception. Whether you’re handling user input, constructing dynamic messages, or working with APIs, understanding how to effectively use the string type is essential. In this article, we’ll explore how strings work in TypeScript, cover common string operations, and look at best practices to make your code cleaner and more robust.

You will learn

  • Basic usage of the string type
  • How to use union types with string values
  • What template literal types are and when to use them
  • Tricky cases

1–) Basic Usage of string type

In TypeScript, basic string usage involves declaring a variable with the string type and assigning it a sequence of characters

 let message: string = "Working with string in TypeScript!";

Note: If you initialize a variable with a value, you don’t need to explicitly specify its type. TypeScript will automatically infer the type based on the initial value.

Message type is string automatically

Message type is string automatically

Note: When you initialize a variable with **const, its type is inferred directly from the assigned value, since `const` **variables cannot be reassigned.

Message type is assigned value directly.

Message type is assigned value directly.

2–) How to use union types with string values

A union string type allows a variable to hold one value from a predefined set of specific string literals, providing more precise type safety and better code clarity.

// union string type for request type
type RequestType = 'POST' | 'GET' | 'PUT'

// Another example with directions
type Direction = "up" | "down" | "left" | "right";

3–) What template literal types are and when to use them

Template literal types in TypeScript allow you to build new string types by combining literal types using the same backtick syntax as JavaScript template strings (${}).

They work similarly to how template strings build dynamic strings at runtime — except here, they define string patterns at the type level.

Custom String Format

We can define a custom string format by using the template literal types. It is similar like regex in JavaScript.

In above example we have to start with ‘get’ and continue with uppercase like:

type GetWhatever = `get${Capitalize<string>}`;

const getApple: GetWhatever = 'getApple'
const getBanana: GetWhatever = 'getbanana' // not Valid
const getBanana2: GetWhatever = 'getBanana' // Valid

Combining Union Types

We can also combine string union type into a string type like:

type Cordinate = 'X' | 'Y' | 'Z'
type Nums = '0' | '1' | '2'

type Cartesian = `${Cordinate}${Nums}`

When we try to use Cartesian type the result will be:

Prefixes and Suffixes

We can use prefixes or suffixes in template literal types to define strict string formats. This is commonly used for things like file names, URLs, or custom identifiers.

type AllowedFiles = `${string}.jpg` | `${string}.png`;

let file1: AllowedFiles = "file1.jpg";  // valid
let file2: AllowedFiles = "file2.png";  // valid
let file3: AllowedFiles = "doc.pdf";    // invalid

Tricky example

Now, lets create an example base on the what we learned so far:

We have a this kind of an type it provides a request ,Now, we will make it better.

type RequestType = {
  method: 'POST' | 'GET'
  url: string
  body: object
}

Actually, that example can do its job like:

const getUserRequest: RequestType = {
  url: 'www.test.com/getUsers',
  method: 'GET',
  body: null
}

But the data can be hacking by using different kind of and data like:

const getUserRequest: RequestType = {
  url: 'testtesttesttest', // seems valid
  method: 'GET',
  body: null, // not needed for GET request
}

Url should be more restrict and body property only available for POST request

Lets make it better:

For url we will apply template literal and restrict it with http request format. For we will enable body field only for POST request

type RequestType = {
  method: 'POST'
  url: `http://${string}.com`
  body: object
} | {
  method: 'GET'
  url: `http://${string}.com`
}

Url should be valid format

Url should be valid format

Body should be available only POST request

Body should be available only POST request

Still we can make it much better, we can make url be common and support https as well.

type RequestType = { 
url:`http://www.${string}.com${string}` | `https://www.${string}.com${string}`}
& ({
    method: 'POST'
    body: object
  } | {
    method: 'GET'
  })

const getUserRequest: RequestType = {
  url: 'http://www.test.com', // seems valid
  method: 'POST',
  body: { organizationId: 2 }
}

Now it is supporting http and https, also body only available for POST request.


메타데이터
post_id
a3db01ba799e
slug
working-with-string-in-typescript-a3db01ba799e
url
https://medium.com/@rdvndmrc/working-with-string-in-typescript-a3db01ba799e
canonical_url
https://medium.com/@rdvndmrc/working-with-string-in-typescript-a3db01ba799e
author_url
https://medium.com/@rdvndmrc
status
ok
fetched_at
2026-06-26 06:47:43