Skip to main content

What is the string type?

What is the string type

The string type in TypeScript represents text data, that is, a sequence of Unicode characters. It is used to store strings - words, sentences, any text values.

Unlike the String object, which is created via the constructor (new String("...")), the primitive string is a true primitive, not an object. TypeScript distinguishes between these two concepts, and you should use the primitive type string.


How to declare a variable of type string

There are several ways:

1. Explicit type annotation

javascript
let message: string = "Hello, TypeScript!";

2. Implicit type inference

TypeScript infers the string type on its own when a string value is assigned:

javascript
let greeting = "Hello!"; // automatically: string

3. Using template literals

You can use backticks to substitute expressions:

javascript
let name: string = "Alex"; let welcome: string = `Welcome, ${name}!`;

Usage examples

javascript
// String concatenation let firstName: string = "Alice"; let lastName: string = "Smith"; let fullName: string = firstName + " " + lastName; // Getting a character let firstChar: string = firstName.charAt(0); // "A" // String length let length: number = fullName.length; // 11

Important

  • Use string, not String:

    javascript
    let s1: string = "text"; // correct let s2: String = new String("text"); // not recommended

Because String is a wrapper object, not a primitive, which can cause unexpected errors in comparisons and checks.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.