Working with Text in TypeScript: A Guide to string vs. String
Here's a breakdown of the key differences:
Feature | string (lowercase) | String (uppercase) |
---|---|---|
Type | Primitive | Object |
Memory Usage | Efficient | Less efficient |
Creation | String literals (e.g., "text") | new String("text") |
Common Use Case | Representing text data | String manipulation (rare in TypeScript) |
let name: string = "Alice"; // Declares a variable 'name' of type string and assigns the value "Alice"
console.log(typeof name); // Outputs: "string" (primitive type)
let message: String = new String("Hello World"); // Creates a String object with the value "Hello World"
console.log(typeof message); // Outputs: "object" (String object)
Issues with type mismatch:
// This line will cause a compilation error in TypeScript
let greeting: string = new String("Hi"); // Assigning a String object to a string typed variable
// Corrected version: create a string literal
let greeting: string = "Hi";
As you can see, the first two examples show how to declare variables with string
and String
types. The third example highlights that you cannot directly assign a String
object to a string
variable due to type mismatch.
Template literals (backticks):
These allow for embedding expressions within strings using
${expression}
syntax. This is useful for dynamic string creation:let name = "Bob"; let greeting = `Hello, ${name}!`; console.log(greeting); // Outputs: "Hello, Bob!"
String methods:
The built-in
String
object (even though you typically avoid it for creating strings) offers various methods for manipulating existing strings. These methods can be helpful for tasks like concatenation, splitting, searching, etc.For example, to combine two strings:
let firstName = "Alice"; let lastName = "Johnson"; let fullName = firstName + " " + lastName; console.log(fullName); // Outputs: "Alice Johnson"
Type Assertions (casting):
In rare cases, you might encounter a scenario where a variable holds a value that you know is a string but might be inferred as
any
by TypeScript. You can use type assertions (cast the type) to explicitly tell TypeScript to treat the value as a string:let userInput = prompt("Enter your name:"); // Input might be inferred as any let userName = userInput as string; // Asserting it's actually a string console.log(`Welcome, ${userName}`);
typescript