Item 10: Avoid Object Wrapper Types (String, Number, Boolean, Symbol, BigInt)
May 10, 2024 ยท View on GitHub
Things to Remember
- Avoid TypeScript object wrapper types. Use the primitive types instead:
stringinstead ofString,numberinstead ofNumber,booleaninstead ofBoolean,symbolinstead ofSymbol, andbigintinstead ofBigInt. - Understand how object wrapper types are used to provide methods on primitive values. Avoid instantiating them or using them directly, with the exception of
SymbolandBigInt.
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));
function getStringLen(foo: String) {
return foo.length;
}
getStringLen("hello"); // OK
getStringLen(new String("hello")); // OK
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.
}
const s: String = "primitive";
const n: Number = 12;
const b: Boolean = true;