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');
primitive === wrapper, the result is false:console.log('hello' === new String('hello')); // false
string, not String).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.
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.