|
The only new runtime feature that Typescript brings to Javascript is enums.* Everything else is just types. Interfaces, for example, are just a way of defining a shape that data will fit to. They are (almost) equivalent to the `type MyType = { key1: string /* etc */ }` construct, and behave more like an ML record type than a Java interface. Also, I don't know what exactly you're describing, but objects as optional named parameters are a common technique in Javascript and therefore very well sorted in Typescript. I'm on my phone so this might not work brilliantly, but something like this: // This could also be an interface... ;)
type Params = {
// These keys are optional
// (Note the question mark)
height?: number | string
width?: number | string
}
class Rectangle {
constructor({height, width}: Params = {}) {
console.log(height, width);
}
}
I've not checked that, but it should type check fine. We need to tell Typescript that the param keys can be optional, I used the question mark here, but if you've already got a type, you can use the Partial<T> type to cover it to having all optional keys. We also need to see a default value if the object isn't passed, but that's true in Javascript as well (otherwise we'd get a runtime exception that you can't destructure undefined).I can definitely empathise with the idea that some Typescript developers just use it as an opportunity to write Javascript-flavoured Java, but this is mostly a stylistic choice (and completely possible in raw Javascript too). But Typescript is very explicitly designed you match the usage patterns of Javascript directly - i.e. if your Javascript code runs (and makes sense), you should be able to write an identical version in Typescript and have it be accepted by the type checker. Obviously that's never going to be entirely the case, but I really find I have many issues porting idiomatic Javascript too Typescript - and where I do, it's usually because the Javascript was wrong in the first place. * That's not actually entirely true, I forgot about field declarations in constructors, but I don't think I've ever seen that used in the wild outside of very old Angular codebases. |
There are a few others, mostly discouraged these days (namespace and module runtime keywords come to mind). Mostly they’ve treated these as legacy mistakes (good!), but they introduced a new one recently that baffles me given that posture: `accessor` as a shorthand for getter/setter pairs, with no clear authoring benefit for working with the underlying private value.