ProgrammingBackend Developer / TypeScript Architect

How are wrapper types implemented and what are they used for in TypeScript? What problems arise when working with primitives and their wrappers?

Pass interviews with Hintsage AI assistant

Answer

TypeScript distinguishes between primitive types (string, number, boolean) and their object wrappers (String, Number, Boolean). Wrappers are objects created through constructors:

const primitive: string = 'hello'; const wrapper: String = new String('hello');
  • Primitives — simple, efficient, have no methods or properties other than built-in ones.
  • Obj-wrappers — objects with corresponding methods/properties, rarely used in business logic.
  • When comparing primitive === wrapper, the result is false:
console.log('hello' === new String('hello')); // false
  • When typing, always try to use primitives (string, not String).
  • Wrappers are applicable only when there is a need to work with generic API libraries (for example, for reflection or metaprogramming).

Gotcha Question

Can wrapper types (String, Number, Boolean) be used in TypeScript interfaces if the values are primitives?

Answer: It is not recommended to use wrappers: in most cases the values will be primitives, and directly inheriting an interface from a wrapper type will lead to errors. It's better to always use string, number, boolean.

Examples of real errors due to ignorance of subtleties in the topic


Story

In a web application for storing full names, the String type was used in the user interface. This led to comparison errors and incorrect unit test passes that required strictly identical types (primitives and their wrappers differ in identity).


Story

A library developer typed a generic function with Number, and library clients supplied primitive values, which caused problems with type guards that unexpectedly did not work for primitives. This resulted in a difficult-to-debug type coercion error.


Story

In an analytical service, the Boolean type was used for the user's active flag, and the comparison result during data filtering was always false, even though visually the values matched. This caused incorrect data processing and report crashes.