DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk2 min

Get and Check String Length in TypeScript

Learn how to read a string’s length in TypeScript, safely check unknown values, and choose the right Unicode counting method.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a string, read text.length. It returns the number of UTF-16 code units in the string—not necessarily the number of Unicode code points or characters a person sees. If a value might not be a string, check it with typeof value === "string" before reading its length.

Get the length of a string

TypeScript builds on JavaScript, so a string’s length property works the same way in both languages and returns a number. A function whose input is already typed as string can access the property directly:

function getStringLength(text: string): number {
  return text.length;
}

For example, getStringLength("hello") returns 5. The TypeScript handbook also uses length in an example involving strings and arrays: TypeScript for JavaScript Programmers.

Check a value before reading its length

A TypeScript type annotation does not validate data at runtime. When a value comes from an API, a form, or another source that may provide a non-string, accept it as unknown and narrow it with a type check:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
function checkedStringLength(value: unknown): number | undefined {
  if (typeof value === "string") {
    return value.length;
  }
  return undefined;
}

Inside the if branch, TypeScript narrows value to string, so accessing value.length is safe. Returning undefined is one possible policy; an application can instead return a validation error or a discriminated result.

Do not use a type assertion such as value as string to make unchecked input appear valid. An assertion changes what TypeScript assumes; it does not check the runtime value. Also prefer the primitive string type over the boxed String type, as the TypeScript handbook recommends: TypeScript: Do’s and Don’ts.

Rank #2
TypeScript Programming Language - Software Engineer & Coder T-Shirt
  • TypeScript implements a superset of syntax for strictly typed development, facilitating deep static analysis and enhanced development environment integration. The compiler translates source into standard script formats, ensuring parity across any runtime.
  • TypeScript is ideal for front-end developers, full-stack engineers, and software architects who build large-scale web applications. It serves those looking to improve code excellence, reduce bugs through static checking, and maintain complex projects more.
  • Lightweight, Classic fit, Double-needle sleeve and bottom hem

Choose what “length” should count

The right method depends on the unit your application requires. JavaScript’s String.length measures UTF-16 code units, while spreading a string counts Unicode code points, and Intl.Segmenter can count grapheme clusters that more closely correspond to user-perceived characters. MDN explains these distinctions in its String.length reference.

Counting method Example What it counts Use it when
text.length "😄".length is 2 UTF-16 code units; a supplementary code point such as this emoji occupies two. The API or limit is defined in JavaScript UTF-16 code units.
[...text].length [..."😄"].length is 1 Unicode code points; a surrogate pair is iterated as one point. Combined sequences can still contain multiple points. You need a simple code-point count rather than a count of displayed characters.
Intl.Segmenter with granularity: "grapheme" MDN’s family-emoji example, "👨‍👩‍👧‍👧", has one grapheme cluster. Grapheme clusters, which are closer to user-perceived characters and can include multiple code points. Your product’s rule is based on perceived characters; confirm support in the target runtime.

A grapheme-cluster count can be computed like this:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
function graphemeCount(text: string): number {
  const segmenter = new Intl.Segmenter(undefined, { granularity: "grapheme" });
  return Array.from(segmenter.segment(text)).length;
}

The locale argument is undefined here, so the runtime uses its default locale. Check that Intl.Segmenter is supported in the environments where your code runs, and follow the exact counting rule required by your product.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Do not confuse a string’s length with the String function’s arity

Read text.length to measure a particular string. String.length refers instead to the number of parameters the built-in String function declares; it is not the length of a string value.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.