I would like to be able create (or extend from String) a TypeScript type that behaves like String.
To be able to assign value like: const object: MyCustomString = 'some value'
Why do you need this? Can't you just store the string in a field of your object?
– Onur ArıApr 08 '19 at 14:53
1
It's not possible to directly do what you want to do. You can modify the String prototype but perhaps a better question is what are you actually trying to do because this sounds like [an XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)
– VLAZApr 08 '19 at 14:53
I think you are looking for branded types: https://stackoverflow.com/questions/49260143/how-do-you-emulate-nominal-typing-in-typescript/49260286#49260286
– Titian Cernicova-DragomirApr 08 '19 at 14:56
I ma trying to represent a XML tag of xliff document
`Some text for translationSome translated text
`
So the tag `` is mainly string but has some attributes and i want to access it like `TranslationUnit.Source = 'Some text to translate'; TranslationUnit.Source.translate=true;`
– MamphirApr 08 '19 at 15:09
The extends keyword can be used to subclass custom classes as well as built-in objects.
So, it is authorized to subclass built-in types in ES2015:
class MyString extends String {
get specialProp() {
return this + " is special!"
}
}
const s = new MyString("abc");
console.log(s.specialProp); // abc is special!
Or, other example:
class SourceString extends String {
constructor(s: string, public translate = false) {
super(s);
}
}
const s = new SourceString("abc", true);
console.log(s.translate); // true
This is near to what i thought.
I found definition of `String` on GitHub [link](https://github.com/Microsoft/TypeScript/blob/2c9f7e6ef1aabc83a25db34adeeaea6da2ddaff6/lib/lib.es5.d.ts#L394) and [link](https://github.com/Microsoft/TypeScript/blob/2c9f7e6ef1aabc83a25db34adeeaea6da2ddaff6/lib/lib.es5.d.ts#L517)
\n I would like something like this if its possible,
when i try to implement the `StringConstructor {...` i get issues with implementing `(value?: any): boolean;`, gives me an error Type `'SourceString' provides no match for the signature '(value?: any): string'.`
– MamphirApr 08 '19 at 19:08
@JackDaniels I'm sorry I can't help with that. The code you post contains a lot of errors. And I can't understand why it would be needed. Just use the code I suggest. Or write another question.
– PaleoApr 08 '19 at 20:09