Logo

What is the difference between String and string in TypeScript?

In TypeScript, string (all lowercase) refers to the primitive string type (e.g., the direct value like "Hello"), while String (capitalized) is the wrapper object type (e.g., new String("Hello")). Typically, you should use string for type annotations because it represents the actual string values in JavaScript. String objects are rarely used and can lead to confusion.

1. string (primitive type)

  • Represents the primitive string type in JavaScript.
  • Examples:
    let text: string = "Hello, world!"; text.toUpperCase(); // Works fine
  • Always prefer using string over String when declaring types in TypeScript.

2. String (object type / wrapper)

  • Refers to the String wrapper object in JavaScript, created via new String(...).
  • Example:
    let objStr: String = new String("Hello"); // This is an object, not a primitive
  • Using String instead of string can lead to subtle bugs or confusion since objStr is not strictly equal to a primitive "Hello" if you use ===.

3. Why Prefer string?

  1. Performance: A String object is more memory-heavy than a primitive.
  2. Behavior: string is typically what you deal with in daily coding.
  3. Idiomatic: TypeScript best practices recommend using the primitive type (string) for your type annotations, as it reflects normal usage in JavaScript.

Example of Differences

const primitive: string = "Hello"; const wrapper: String = new String("Hello"); console.log(typeof primitive); // "string" console.log(typeof wrapper); // "object" console.log(primitive === wrapper); // false

They are not === equal because one is a primitive and the other is an object.

4. Summary

  • string → The primitive type, recommended for TypeScript annotations.
  • String → The JavaScript wrapper object type, rarely needed in typical TypeScript code.

Also, if you’d like to build a stronger foundation in JavaScript (on which TypeScript is built), consider the Grokking JavaScript Fundamentals course by DesignGurus.io. It covers core concepts like prototypes, closures, and async patterns—helping you better understand how TypeScript’s types align with underlying JS behavior.

CONTRIBUTOR
TechGrind