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
let message: string = "Hello, TypeScript!";2. Implicit type inference
TypeScript infers the string type on its own when a string value is assigned:
let greeting = "Hello!"; // automatically: string3. Using template literals
You can use backticks to substitute expressions:
let name: string = "Alex";
let welcome: string = `Welcome, ${name}!`;Usage examples
// 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; // 11Important
-
Use
string, notString:javascriptlet 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 readyA concise answer to help you respond confidently on this topic during an interview.