Back

Working with string in TypeScript

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

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.

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

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";

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.

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

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}`
// output:
// type Cartesian = 'X0' | 'X1' | 'X2' | 'Y0' | 'Y1' | 'Y2' | 'Z0' | 'Z1' | 'Z2'

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
}

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.

Back