A way to express that a method must be overriden #43910
Labels
Awaiting More Feedback
This means we'd like to hear from more people who would be helped by this feature
Suggestion
An idea for TypeScript
Suggestion
In Javascript it is possible and encouraged in documentations like MDN to override
toString
andvalueOf
for custom objects, because the version inherited fromObject
is not very useful (the dreaded[object Object]
).However, there is to my knowledge no way to express in a type that a class must override those methods (or that an object must have them as own properties) and therefore no way to know if they are reliable.
🔍 Search Terms
method overriding, toString, own property
✅ Viability Checklist
My suggestion meets these guidelines:
⭐ Suggestion
An idea would be to have a
own
modifier which would basically compare a property name with the list produced by the following functionI think it reads well:
📃 Motivating Example
Having a useless
toString
is borderline a Liskov substitution violation and Javascript users have learned to not rely on it. Typescript could come to the rescue.The modifier would also make it easy to reject
Object.create(null)
.I have been reading some Haskell lately and I was envious of the confidence the type class
Show
gives haskellers, but it is built in. Javascript usestoString
for type coercion and I believe it makes more sense to try to achieve that level of confidence by fixing it.I don't know in what other circumstances one would require that a method is overridden as it would indicate that the base class's method is not suitable, which would be a red flag, but my lack of imagination is no proof that it can't be useful in other situations.
💻 Use Cases
Having a polymorphic way to query a string from an object.
Currently one would need to implement a custom method or signify by some tag that
toString
is safe to use, and the user of the object would need to know about this tag/custom method.We can imagine generic functions like a sorting function which default to converting an object to a string in order to deal with it, but only if it is a usable string. The IDE would advertise by the function definition in the tooltip that it is possible to pass an object as long as it implements
toString
, which would make the user happy as it would potentially clean up some code in many places.The text was updated successfully, but these errors were encountered: