I'm a Python software engineer and a beginner with Typescript, currently in the process of developing an Angular application. Every now and then I'm facing surprises concerning my understanding of why and how to use classes and instances and I'm looking for seasoned advice. Specifically, consider a class like:
class User {
constructor(public name: string, ...many more instance attributes);
upperCase() {return this.name.upper();}
// ...many more methods that use instance state
}
- Is it good practice to make sure that every instance of a typed object in use throughout the application is a "real" class instance as opposed to an object that just matches the "shape"?
- For example, should every HTTP service do something like:
return http.get<User>.pipe(map(user => new User(user)))
so that clients can be sure what they are actually dealing with, instance checks always perform as expected and missing methods do not raise errors?
- Is this considered cumbersome (maybe especially with nested objects)? From the few projects i've seen I don't really have the feeling they care about this too much!?
- How can the static type checking work properly when objects aren't "real" instances with regards to methods.
- Should OO be kept simple with regards to methods and instance state manipulation/functionality and instead classes should mainly serve the purpose of "shape checking" (i guess being called DTO then!?)
- There are certainly hints every now and then (for example the official guide to mixins) that make me question if I should rely on classes in Typescript as I would in other languages or just name them DTO and use them as shape checking convenience, while implementing most functionality more procedurally in type annotated functions (so that only the shape matters)?
Typescript is structurally typed, not nominally typed as you are used to and what you seem to be trying to get back to.
The best practice here is to follow the philosophy of the language, don't try to fight it. Try to get used to structural typing and after a while you'll probably be comfortable with this approach to typing as well.