Lesson 12 of 60 – String Type
20%

String Type in TypeScript

The string type is used to represent text in TypeScript. A string can contain letters, words, sentences, symbols, and other textual data.

Note: In TypeScript, you can explicitly specify string as the type of a variable or allow TypeScript to infer the type automatically.

1. What is a String?

A string is a sequence of characters used to represent text.

let name: string = "Rahul";

Here, "Rahul" is a string value.

2. Declaring a String Variable

You can declare a string variable using let.

let city: string = "Patna";

console.log(city);

The type annotation string tells TypeScript that city should contain text.

3. String with const

You can also create a string constant using const.

const country: string = "India";

console.log(country);

The variable cannot be reassigned because it is declared using const.

4. Double Quotes

Strings can be written using double quotation marks.

let name: string = "Rahul";

let course: string = "TypeScript";

Both values are strings.

5. Single Quotes

Strings can also be written using single quotation marks.

let name: string = 'Rahul';

let course: string = 'TypeScript';

Single quotes and double quotes can both be used for strings.

6. Template Literals

Template literals use backticks `. They are useful when creating strings that contain variables.

let name: string = "Rahul";

let message: string = `Hello ${name}`;

console.log(message);

The output will be:

Hello Rahul

7. String Type Annotation

You can explicitly specify the string type using a type annotation.

let studentName: string = "Amit";

let courseName: string = "JavaScript";

let city: string = "Patna";

All three variables are explicitly typed as strings.

8. String Type Inference

TypeScript can automatically determine that a variable contains a string.

let name = "Rahul";

TypeScript infers the type of name as string.

9. Changing a String Variable

A string variable declared using let can be reassigned to another string.

let city: string = "Patna";

city = "Delhi";

console.log(city);

The new value must still be a string.

10. String Cannot Receive a Number

A variable typed as string cannot receive a number.

let name: string = "Rahul";

// Error
// name = 100;

TypeScript prevents incompatible values from being assigned.

11. Empty String

An empty string contains no characters.

let message: string = "";

console.log(message);

The variable still has the type string.

12. String Length

The length property returns the number of characters in a string.

let name: string = "Rahul";

console.log(name.length);

Output:

5

13. Convert String to Uppercase

The toUpperCase() method converts letters to uppercase.

let name: string = "rahul";

console.log(name.toUpperCase());

Output:

RAHUL

14. Convert String to Lowercase

The toLowerCase() method converts letters to lowercase.

let name: string = "RAHUL";

console.log(name.toLowerCase());

Output:

rahul

15. Concatenating Strings

String concatenation means joining two or more strings together.

let firstName: string = "Rahul";
let lastName: string = "Kumar";

let fullName: string =
    firstName + " " + lastName;

console.log(fullName);

Output:

Rahul Kumar

16. String Interpolation

Template literals make it easy to insert variables into strings.

let name: string = "Amit";
let course: string = "TypeScript";

let message: string =
    `My name is ${name} and I am learning ${course}.`;

console.log(message);

17. Accessing a Character

You can access a character using its index. The first character has index 0.

let name: string = "Rahul";

console.log(name[0]);
console.log(name[1]);

Output:

R
a

18. String Includes Method

The includes() method checks whether a string contains another string.

let message: string =
    "Welcome to TypeScript";

console.log(
    message.includes("TypeScript")
);

The result is true.

19. String Starts With

The startsWith() method checks whether a string starts with a specified value.

let message: string = "Hello World";

console.log(
    message.startsWith("Hello")
);

The result is true.

20. String Ends With

The endsWith() method checks whether a string ends with a specified value.

let message: string = "Hello World";

console.log(
    message.endsWith("World")
);

The result is true.

21. Removing Extra Spaces

The trim() method removes spaces from the beginning and end of a string.

let name: string =
    "   Rahul   ";

console.log(name.trim());

The output is:

Rahul

22. Finding Part of a String

The substring() method can extract part of a string.

let text: string = "TypeScript";

let result: string =
    text.substring(0, 4);

console.log(result);

Output:

Type

23. Replacing Text

The replace() method can replace part of a string.

let message: string =
    "Hello Rahul";

let result: string =
    message.replace(
        "Rahul",
        "Amit"
    );

console.log(result);

Output:

Hello Amit

24. Strings in Functions

Functions can accept string parameters and return strings.

function greet(name: string): string {

    return `Hello ${name}`;

}

console.log(
    greet("Rahul")
);

25. Strings in Objects

String values can be stored inside objects.

let student: {
    name: string;
    course: string;
} = {

    name: "Amit",
    course: "TypeScript"

};

console.log(student.name);
console.log(student.course);

26. Strings in Arrays

You can create an array containing multiple strings.

let students: string[] = [
    "Amit",
    "Rahul",
    "Priya"
];

console.log(students);

Every element in this array is a string.

27. Strings in React Native

Strings are commonly used for text displayed in React Native applications.

import { Text } from "react-native";

const appName: string = "Student App";

function App() {

    return (
        <Text>
            {appName}
        </Text>
    );

}

Here, appName is explicitly typed as a string.

28. Strings in React Native TextInput

Text entered by a user is commonly handled as a string.

import { TextInput } from "react-native";

let userName: string = "";

<TextInput
    value={userName}
/>

This concept is useful when building login forms, registration forms, and other React Native applications.

29. Common String Mistakes

Mistake 1: Assigning a number to a string variable.

let name: string = "Rahul";

// Error
// name = 100;

Mistake 2: Calling a string method on a number.

let age: number = 20;

// Incorrect
// age.toUpperCase();

Always make sure that the value and the operation match the type.

30. String Type Summary

Feature Example
String annotation let name: string = "Rahul";
String inference let name = "Rahul";
Length name.length
Uppercase name.toUpperCase()
Lowercase name.toLowerCase()
Contains text name.includes("a")
Remove spaces name.trim()
Combine strings first + last
Remember: The string type is used for text values. TypeScript can either infer a string type automatically or you can specify it explicitly using : string.

📌 Key Points

  • The string type represents text in TypeScript.
  • Strings can use single quotes, double quotes, or template literals.
  • You can explicitly declare a variable as string.
  • TypeScript can also infer string types automatically.
  • String variables can be changed when declared with let.
  • String constants declared with const cannot be reassigned.
  • The length property returns the number of characters.
  • toUpperCase() converts text to uppercase.
  • toLowerCase() converts text to lowercase.
  • Strings are widely used for text, forms, React, and React Native applications.

🧠 Quick Quiz

Question: Which TypeScript type is used to store text?