I was wondering if it's possible to attach a method to a primitive (e.g., a string) while still being able to use it as the primitive. Note: this is different from adding methods to the String class as described in other questions (e.g., Extend a String class in ES6).
For instance, here's some dummy code of what I've been trying. Essentially, I could wrap the primitive in a class, add methods to that class, the somehow still be able to access the underlying value automatically?
class MyString {
value: string
constructor(value) {
this.value = value
}
get5thCharacter() {
return this.value[4]
}
}
const hello = new MyString("hello")
const world = "world"
// desired results
console.log(hello + " " + world) // "hello world"
console.log(hello.get5thCharacter()) // "o"
console.log(world.get5thCharacter()) // TypeError: world.get5thCharacter is not a function
Notice also that while world
is also a String, world
does not have the method I defined on hello
, despite the fact they can both otherwise be used as strings.
Any thoughts?