Skip to content

Latest commit

 

History

History
57 lines (42 loc) · 2.38 KB

avoid-object-wrapper-types.md

File metadata and controls

57 lines (42 loc) · 2.38 KB

Item 10: Avoid Object Wrapper Types (String, Number, Boolean, Symbol, BigInt)

Things to Remember

  • Avoid TypeScript object wrapper types. Use the primitive types instead: string instead of String, number instead of Number, boolean instead of Boolean, symbol instead of Symbol, and bigint instead of BigInt.
  • Understand how object wrapper types are used to provide methods on primitive values. Avoid instantiating them or using them directly, with the exception of Symbol and BigInt.

Code Samples

// Don't do this!
const originalCharAt = String.prototype.charAt;
String.prototype.charAt = function(pos) {
  console.log(this, typeof this, pos);
  return originalCharAt.call(this, pos);
};
console.log('primitive'.charAt(3));

💻 playground


function getStringLen(foo: String) {
  return foo.length;
}

getStringLen("hello");  // OK
getStringLen(new String("hello"));  // OK

💻 playground


function isGreeting(phrase: String) {
  return ['hello', 'good day'].includes(phrase);
  //                                    ~~~~~~
  // Argument of type 'String' is not assignable to parameter of type 'string'.
  // 'string' is a primitive, but 'String' is a wrapper object.
  // Prefer using 'string' when possible.
}

💻 playground


const s: String = "primitive";
const n: Number = 12;
const b: Boolean = true;

💻 playground