TypeScript Reference ยท Primitive and Special Types
The TypeScript string type
Reference for the string type in TypeScript: literals, template strings, common methods, immutability, string vs String and literal types.
string is the type of all text values: a sequence of UTF-16 code units. Single quotes, double quotes and backticks all produce a string; backticks add interpolation and multi-line text. Strings are primitives and immutable, so every method that seems to change a string returns a new one.
TypeScript infers string for mutable bindings (let) and a string literal type such as "north" for const bindings. Always write the lowercase string, never the wrapper type String.
let title: string = "Handbook"; const direction = "north"; // type "north" const greeting: string = `Hello, ${title}`;
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
let value: string; const literal: "yes" = "yes"; type Id = `user-${number}`;
| Form | Description |
|---|---|
string |
Any text. Assignable from string literals, template expressions and results of string methods. |
"abc" |
A string literal type: only that exact text. A const declaration infers it. |
`x-${number}` |
A template literal type: a pattern of strings. |
String |
The wrapper object type. Avoid it; a primitive string is assignable to String but not the reverse. |
Usage notes
- Assignability. A literal type is assignable to
string, butstringis not assignable to a literal union; useas const, a union annotation or a type guard. - Widening.
let x = "a"widens tostring;const x = "a"keeps"a". Properties of object literals widen too unless you writeas const. - Indexing.
str[i]has typestring, even wheniis out of range, unlessnoUncheckedIndexedAccessis on (thenstring | undefined). Preferstr.at(i), which is typedstring | undefined. - Length is in UTF-16 units. Emoji and many scripts take two units; iterate with
for...ofor spread to count code points, andIntl.Segmenterfor user-visible characters. - Comparison.
===compares by value;<and>compare code units, not language-aware order. UselocaleCompareorIntl.Collatorfor sorting names. - Building text.
+=in a loop is fine in modern engines; for very large output collect parts in an array andjoin. - Not a number.
"5" + 1is"51"; convert explicitly withNumber()orparseInt. - Methods like
replaceAll,atandisWellFormedneed a library target new enough (lib: ["ES2024"]or later).