246 points · by jgwil2 · 5y ago · 240 comments
That's one thing I like about T, it's very self evident that it's just 'the' generic type. But maybe I'm just used to it. With multiple generic types I can see how longer names would be useful.
fn square(numberToBeSquared : number): number {
return numberToBeSquared * numberToBeSquared;
}
The one letter variable version of the function is perfectly readable. Most generics aren't used in a significantly complicated way. Sure, maybe if you're doing something like Haskell's lenses, then you should use descriptive names might be better, but how often are you writing type Lens s t a b = forall f. Functor f => (a -> f b) -> s -> f t
and is type Lens source dest gettable settable =
forall structure. Functor structure =>
(gettable -> structure settable)
-> source
-> structure dest
really any easier to read?public delegate TResult Func<in T,out TResult>(T arg);
(Java has others like just like how every time you open a Gradle project you can expect someone has invented yet another unique way of structuring build files for this repo. :)
I started off in .NET and when I was using Java it wasn't immediately obvious what types were interfaces or not (e.g. "List" is an interface in Java, and also especially when the interface suggests what the implementation is).
C# can be described as a considerably better Java - but I wish they didn't inherit Java's interfaces vs. classes model and instead had something that enables some form of structural-typing: something like TypeScript's interfaces or Swift's protocols.
Rust convention is to mostly use this style of single-letter generics, but not to shy away from using longer names like regular type where useful (but not to prefix them like TFoo).
`Element` is as non-descriptive as `T` in the author’s example and, IMO, doesn’t add any tangible benefit.
When I see a lower case single letter, I assume either a loop control or an enumerator var.
When I see an upper case single letter, it's a generic.
The latter scenario being that hopefully the person debugging your logic a decade from now has some insight into what you were thinking, namely.
Code that has more characters just takes longer to read over and process as well e.g. having to mentally match up which variable names are the same and spotting patterns. Yes, use descriptive names where it helps which is the vast majority of the time, but for small functions where from context it's obvious e.g. `i` can be better than something like `customerReportIndex`, as well as your T example for a general type. Maths proofs would be tiring to read with long names for all the variables for example.
I recently switched back to JS for a prototype of a programming language.
I immediately felt more productive.
At times, the TS systems feels like a theorem prover. Until it doesn't. And then you're left with a bunch of types that almost do what you want... but not quite; Always tempted to experiment again for a day or two.
But let's see what happens down the road. Maybe I'll miss the incidental documentation the typings provide.
With TS its like you’re writing the unit test and your code at the same time, and if your types are expressed well enough you can also skip the compile+run+verify step.
I’ve had cases where I would spend days just writing code, refactoring and iterating, without building the project once, compile it at the end, and have a complex feature work correctly on first try, passing all the functional tests.
It’s like I have a pair working with me constantly compiling my code and pointing out syntax and interface errors while I concentrate on the business logic and big picture stuff.
When I go back to JS it’s as if I now have to do all that manual labour too, as well as constantly write and run unit tests myself to make sure what I write actually works.
Though it definitely took some time to get this comfortable with the TS type system.
It took some getting used to because things end up a bit less obvious, but I found that with the IDE's syntax highlighting capabilities, actually inspecting the inferred types isn't as much of an issue. And then you spend less time typing out type names.
Always tempted to experiment again for a day or two.
Maybe that's it. I've never felt bad about settling for 95% of the benefits of static typing and slapping any/unknown on the edge cases.
Part of good language design is attempting to minimize bad programming habits. In this case, a language with a HM type system would avoid the issue all together, while affording the same productivity gains from having static types.
In code consuming types I relie on inference 80% of the time, sometimes I need to specify generics, if it fails I do dirty casts, if that fails I do dynamic blocks.
Thankfully, the impulse to waste time trying to come up with the most precise typing possible for everything hasn't been as strong with TypeScript as it used to be with Haskell for me. In part that's because TS's type system is so ridiculously expressive that I can say what I want to say without spending too long on it anyway, in part it's because the system's proud unsoundness and the ability for typings to simply be wrong means that I know not to stake my life on the types anyway. Besides, in my experience, the more precise I try to make the types at an interface, the more I need to cast in the internals. Better to find a balance that keeps both reasonable.
Isn't that exactly why you use types to begin with?
https://blog.isquaredsoftware.com/2019/11/blogged-answers-le...
I also try not to let any escape function boundaries.
Recast it to something better when returning something.
No it doesn’t. You’re casting to `any` and hiding that fact. Both top types can be anything at all, `unknown` is only safer if you narrow it to something else by testing it. If you cast it to something else you’re just treating `unknown` as `any`.
But yeah, sometimes you hit a wall and need to do something unsafe.
If we couldn't do something 100% type-safe then we weren't supposed to do it at all. I kid you not.
I got off of that project as soon as I could manage without burning a bridge. Funny thing was that before that? I thought I was quite the stickler for getting types as correct as possible. Turns out I was off by an order of magnitude of what a real "stickler" for correct types could be...
The only downside of burning bridge is that now, I don't have an overview on how bad shape this project is.
Probably just means you are smart and good at testing at some level ;-)
For me the biggest benefit of TypeScript is probably when I debug or extend other peoples code (i.e. all the time) and I don't have to hunt down calling functions to see what gets passed in.
I mostly work on large projects written by other people over the course of years and often this simple thing can save me several minutes several times a day.
I found it far more productive that going through rabbit hole of TS and its compiler. I write my `definitions.d.ts` for my objects, and use them simply
/** @type {ns.MyType} identifier */
const identifier...
and voila, my IDE gives me auto-completes and warns me when I'm doing silly stuff.It works for functions as well using
/** @param {type} parameter name */
and is generally a good idea to use.It gets you 80% of the way there with no compiler/transpiler (although one might argue that the IDE is compiling non-stop on file saves, with its language server).
I embraced Typescript when it was new and the Javascript standard was a total mess. It was leaps and bounds ahead and closer to something like AS3. At the time TS was godsend.
Today, JS + webpack gets you really far using the latest ECMAscript standards.
Same with IDE. The amount of stuff my IDE can deduct based on my few typings and my use of modern strict javascript has strongly reduced the need for another transpiler (on top of webpack).
I found jsDoc to be a perfect 80-20 solution.
Because at the end of the day, TS isn't a compiler, it's a transpiler. You're not compiling to bytecode in a vm, you're still in javascript.
This saves my bacon in the front-end. For the back-end, I most definitely choose a strongly typed language like Go.
My team was really happy with the result, but I'm afraid that if layoffs happen, I'll be on the shortlist.
But someone calling themselves startup-cto.net should be a lot more pragmatic about the value of strong types and willing to embrace the possibility of change!
Writing types give me more pleasure than it should... but if something is hard to type and unlikely to be referenced outside the local scope, it often isn't worth the effort.
I feel in that case you should have some type union of `"notAsked" | "none" | { t: "some", v: "Name" }`, because that would be more clear of what each possible value means. Let `null` and `undefined` be synonyms for `nil`.
I actually created a `type Optional<T> = T | null` for one of my projects because I wanted a good way to describe something that is null vs undefined. This is specially important if you are de/serialising objects. In my case, undefined = user did nothing to it, null = user actually chose not to supply value (and yes, they are different)
You'll need to write undefined as a potential type for potentially undefined object members, and as such it means exactly that - undefined.
For everything else there is null.
A sanity check would be - undefined can only appear in a function parameter type or object member type as a union with other types, or in a === comparison. For everything else there is null.
Explicitly defining something as `undefined` is paradoxical and IMO should never be done. I've tried to explain this concept to some co-workers without much lasting success, but it's a pretty common concept to other languages.
Undefined should basically never be used as a value directly.
map.get("missingKey") returns undefined.
The new ?. operator returns undefined, even if you pass it null.
Undefined means that you don't have to care about the difference between { foo: undefined } and { }.
The only pain point is that JSON.parse() produces null, but this is relatively easy to work around.
I don't find any reason to ever produce a null. I just treat it as a value that can occur when using certain APIs.
If your code depends on the difference between a missing key and a missing value, probably you should be using a Map which makes that difference explicit with separate set() and delete() methods.
null: the value exists but is not set.
undefined: the value does not exist.
JSON.stringify on an undefined property removes that property.
JSON.stringify on null keeps that property as null.
A codebase that does not distinguish between null and undefined is a less flexible codebase.
At the end of the day it would have been much nicer for there to only have been one nothing type but what’s done is done.
Element.{firstChild, nextSibling} being null means “I know what firstChild (or nextSibling) is, but this element doesn’t have one.”
It would be categorically wrong for things like Element.{firstChild, nextSibling} to be undefined.
Except, you can still differentiate between them:
> ({ foo: undefined }).hasOwnProperty('foo')
true
> ({ }).hasOwnProperty('foo')
false
So now you have two ways of specifying a missing property, instead of one. null vs. undefined is a really annoying language misfeature to me, especially with some of the other weird behaviors that it has: > [].length
0
> [].map(v => 123)
[]
> [].map(v => 123).length
[]
> [undefined].length
1
> [undefined].map(v => 123)
[123]
> Array(1).length
1
> Array(1).map(v => 123)
[]
> Array(1).map(v => 123).length
1
If you need to remove a property from an object, just use delete obj.foo; instead of setting it to undefined. JSON.parse(JSON.stringify(obj)).hasOwnProperty('foo')
false
Thing is, other parts of the code might actually serialize and unserialize objects. If you rely on a prop being 'undefined' meaning "prop is unknown like the firstName", as OP suggested, you might be in for a surprise."Less flexible" != "Less correct" or even "less good".
It's true that these are subtly different concepts. It's arguable whether they are helpful distinctions for the long-term health of a codebase.
Sorry if I am misunderstanding your statement.
T | null signifies that it can be cleared by using setState({prop: null}).
T | undefined means that it may start out undefined, but if it becomes defined it'll probably stay that way. If you try doing setState({prop: undefined}), it won't work.
Some of the rebuttals below seem to be saying "But I use them differently!" Bully for them, but 99% of the time when it's not set, you don't really care why it's not set because it's not defined yet or because it's been set to `null`.
And any time they assume it can only be null OR undefined but not either, there's a chance for a bug. Even if I "know" it can only ever be null and not undefined, it's safer to just say != null rather than !== null.
Treating them differently in a code base is a legit semantic, but testing with != null works no matter the intended semantics.
The semantic differences seem to be local at best. In any case, there's plenty of code that legitimately doesn't concern itself with any of that.
I've never ever run into this because I never use undefined for anything other than stuff that's explicitly not set, and I have no fucking idea why other people are. But I can definitely see it causing bugs if you do stuff like use '!=' everywhere and treat null and undefined as the same thing.
This is why the original comment is wrong. You should be narrowing your types where possible. It costs nothing to just always use null if you're explicitly setting something, then you can use '!==' wherever you want, which means that if someone else sets something to undefined you'll catch the bug straight away when it's easiest to catch.
If you treat them the same you're just asking for some 3rd party lib to do a '!== null' or accidentally overwrite a "null" with a default parameter you're not expecting, and that's way, way harder to troubleshoot.
Of course, TypeScript will say that 'null' can't be passed to createNewMessagesResponse directly. However, data gets pushed around a code base a lot and might go through third party packages or come in from an API response and could very well be 'null'. I proactively don't check for 'undefined', because I can't really trust this to be 'undefined'. Furthermore, in the example OP provided, 'null' and 'undefined' should have the same result (no message is shown, because no number was passed to the function).
I see more room for error with being explicit as a default than generalizing as a default.
However, the type guard section seems a bit off to me. Is the suggestion to check each and every property of `Product` in `isProduct`? Seems a bit verbose.
I tend to use Axios, which uses generics to set the payload return type (obviously, some trust in your API responses is needed here):
axios.get<Product[]>(...);In our team we use io-ts to validate all of our endpoints, but simple type guards could achieve the same goal.
I also use axios, and I also take advantage of the generics you've shown above, but I acknowledge that I'm essentially just saying "Trust me" and doing a cast when I do that.
And I'll add - that exact style of code has been a source of bugs in our production codebase before. A dev will pick the wrong type for the axios generic, and if the api response happens to overlap on the used fields, no one notices. Then it blows up 6 months later when someone tries to access a field on the defined type that wasn't actually returned in the api response.
We use it to great effect ourselves, by generating types for axios.
https://github.com/ovotech/laminar/tree/main/packages/lamina...
Now granted, you’re now trusting the api writers with their contract, but if its another team in the org we’ve found it to be warranted.
Very much this. That scenario will break if e.g. the backend API changes. This is a constant source of frustration for someone I know, whose backend team has a habit of not communicating their changes to the frontend team.
There's nothing TS can do to enforce that the actual type of the response matches what the type declaration says (hence the need for runtime checks in this case).
Checking for the existence of a key on an object is dirt cheap.
Even if you happen to have a case where it is expensive, there's absolutely nothing that says your typeguard has to take that approach.
I've seen some reasonably sane code that just checks that the 'Type' field of the object matches the expected value, and the 'Version' field is the right number. It's not going to catch all the possible errors there if someone breaks the api contract, but it's a lot better than a raw cast.
In most cases it's worth it to trade the small performance penalty for correctness, especially since the cost of fetching data is already dominated by the network and backend.
Tbh the bench here suggests the only non algo perf worth doing would be switching to rust with pre allocated memory for each request. By the time we are up to the scale where the sin le digit gains are worth it we'll have more than enough capability for going straight to the software end zone.
I can see how the proposed solution could be "better", but I'd rather avoid the validation code and instead get the type right.
I think we need to have a discussion about the benefits of dynamically typed languages and why many people purposely choose them over statically typed ones.
In my experience, 95% of the time TS would not have helped anything. And the other 5% where it would have is not worth the constant work required to type the whole application. And sure you can use ts just a little bit... but everyone knows that organizationally the pressure then begins to use TS for the whole app.
Types are nice in some circumstances but are they really worth it? I feel like the answer is no for the majority of applications.
Which is kind of sad and against the origins of TS, which meant to supplement JS without bringing all that uncool into the school.
Sometimes I dig into source of a supposedly JS library and witness the author not just the type-checking, but OOPy interfaces, private/public, and I again feel the itch that this superset is a more refined embrace, extend, and extinguish.
Also "don't use 'any'" - there are a lot of edge cases where this can be very difficult to avoid. Even the TS experts have failed to help me figure out how to remove some "any"s. I'm sure there is a correct way, but it just shouldn't be that difficult.
Someone who talks intelligently about the strengths of dynamic languages is Rich Hickey. His talks challenge some of the ideas where static typing is superior to dynamic typing. He is arguably biased in his position but it makes for a refreshing contrast to the static types argument.
Clojure is a great example of the qualities required to make dynamic typing really powerful, the main one being the large library of functions that can operate over all collections. This reduces the amount of custom code you write for data munging, reducing surface area for bugs.
The complete counterpoint to that is Go with no utilities for doing common data transformations, forcing users to re-implement similar logic repeatedly. It may as well be statically typed at that stage to avoid mistakes from writing the same code over and over.
The more powerful statically typed languages with generics then fall somewhere in the middle where you don't have to repeat yourself as much.
I don't get the example for #3. I understand using "unknown" instead of "any", but both examples look effectively the same in terms of type safety.
I also don't get the example for #4. Side effects are the inherit "blind spot" of TypeScript. If you're really worried about your API changing on you, it seems like you'd be better off modeling it in something like JSON schema. Unless maybe your API is trivial.
What type guards are good for is marrying the compile time checks with runtime safety. They allow TSC to infer that in a given code path, the type can be narrowed down to something more specific. This is nice because it lets a single function e.g. handle a few different types without littering your code with `as` or `!`.
For #7, in a lot of (most?) cases, the name of a generic isn't meant to be descriptive. I'd argue that functions that expect it to be are doing it wrong. If I have a `function reverseArray<T>(arr: T[])`, the point of T is that it can be anything. Saying `reverseArray<ArrayTypeToBeReversed>` serves no purpose.
TypeScript also really, really needs to have a strict typechecking mode. Yes I know the "it compiles to raw JS" arguments, but it could easily add extra checks in the JS code (basically what example #4 shows).
Unknown is basically asking the dev to confirm the choice (ideally through a typeguard, but also with a simple cast).
And if you're using a typeguard, just define the argument as 'any' ex -
type AType = {
c: string
}
let a: unknown = {
c: 'test',
}
if (isAType(a)) {
console.log(a.c) // no type errors!
}
function isAType(a: any): a is AType {
return typeof a.c == 'string'
}`map<A,B>(fn:(el:A)=>B):B[]`
Your example is clear enough because the signature is simple, but in more complex functions I've found that becomes obscure real fast, particularly if types are then passed down to something which also uses generic types. Enabling people to reason about things is not as clear as actually telling them what it is. If the 2nd of 3 generic types is the return type for whatever reason, call it SomethingReturn type and remove that ambiguity.
What would the alternative look like in what you wrote? In and Out? Range and Domain? Generic type variables are often too abstract to give a sensible name to.
This is the one "bad habit" that I think is a bit silly - naming conventions can vary by project.
"But do long names even help? I imagine, in such a project the system of logic can be so complex that a new dev cannot use them to their intent without completely understanding the code."
Meaningful names help a person gain an understanding of the code. And that's not even getting into whether or not "completely understanding the code" is a tractable goal in the first place (I don't think it is, even for the people who wrote the code, much less those who come later)
Even in your example, I'd rather read this:
map<IN,OUT>(fn:(el:IN)=>OUT):OUT[]
Plus, it really is a habit. If you stop doing it for these kind of examples that really are very generic, maybe people wouldn't also use only one letter for cases where there is more of a difference between them.
> Do you also use one letter variables and parameters?
A question in response to your question... Do you ever give an ALL CAPS name to a class? Why not?Maybe it's the set of conventions I'm used to, but I find T, U, V familiar and IN, OUT jarring and dramatically less readable at a glance.
`fork<A,B,C>(fn1:(el:Iterator<A>)=>B,fn2:(el:Iterator<A>)=>C)`
For generic that doesn't have any specific meaning we can use T.
Adding a meaning to meaningless generic will add confusion, like in the example, Element might conflict with HTMLElement while it can be something else entirely.
Seems like for "6. Optional properties"
One should rather use tagged unions (see: Abstract Data Types, variants) that are usually written like this in TS:
type Product =
| { type: 'digital', id: string, sizeInMb: number }
| { type: 'physical', id: string, weightInKg: number }
At least I find it more elegant, concise and fun to work with :)Or if brave enough to dive into the deep end of FP, io-ts is nice. https://github.com/gcanti/io-ts
Tagged unions might get a bit messy if you ever need to extend them, but sometimes you simply have some source / sink of data that requires a variant type.
2. The recommendation goes too far in suggesting fallbacks in the parameter list (and would if it had suggested the same for destructuring options/objects generally), without explaining that for some braindead reason fallbacks aren’t `null` safe.
3. This leads into #4 but if readers leave here they’ll think the cast from `unknown` is somehow safer. I have seen this happen, people just cargo cult stuff. I’d much rather a 9-length list than risk that.
5. This particular problem/example is spot on but I’d like to expand the “in tests” scope to explicitly explain why some unsafe types are justified in tests. I always specifically unlint rules about non-null assertions in test because a non-null assertion is an additional safety mechanism in that context: it validates that the runtime agrees with the type system. If you intentionally but explicitly bypass the type system and don’t see an error you should know that’s a bug and fix it.
7. Is mostly spot on but conditional. There are unfortunately a lot of conventions at play. Anytime there’s ambiguity definitely add verbosity. If your type is truly generic without constraint adding that verbosity is actually harmful.
10. This is just plain wrong for the vast majority of cases. It’s also a JavaScript-ism that doesn’t translate well to other languages and the “bad” habit helps avoid mistakes. For most use cases `null` should only have one meaning: absence of a value. The cases where it doesn’t are almost always a mistake (oops this was an “object”), and the cases where the distinction does matter are usually (but not always) a sign that your interface is bad (the exception being explicitly passing `null` sentinel values to overwrite existing data in a stateful external system like a database). This should be the exception not the rule and making it syntactically clear is useful.
TypeScript will believe what you tell it in a type guard's signature without looking at the body of the function further than "does it return a boolean".
I don't quite understand the criticism. You may as well say that unit tests are just as unsafe as not writing unit tests, because your test might not do what you think it's doing.
I elaborate on ways to use them effectively in the post.
Type guards have a runtime overhead, don't they?
(You could argue: "If TS can not infer the type at this point so neither can you. Better to check at runtime." But from my experience, sometimes TS is simply not smart enough.)
Does JS need a better way to introduce json type safety? C# and graphql use schemas, I wonder if this is a better approach (compile time, not run time).
But yes: I think TS is missing a way to derive runtime functionality from the type definitions - at least in the cases, where the types describe plain JSON.
Something along the lines of clojures' `spec`.
type Spec<T> = T extends (x: unknown) => x is infer U ? U : never;
type Foo = Spec<typeof someTypeGuard>;(I can think offhand of one case in the last year where I've wanted to use a type guard for a reason that didn't have to do with runtime validation, anyway. Even then, it wasn't the solution I ended up going with.)
In most contexts, the reasonable approach would be to only do runtime validation at your system boundaries and not anywhere inbetween.
Thinking about how to solve this, it occurred to me to use a type guard, since it would have effectively convinced the type checker that my object instance was in fact an instance of the class of which it is an instance. But it would've been a wart and also imposed the aforementioned runtime overhead - not that that would've been meaningful in this case, it wasn't in a hot loop or anything, but I still didn't like it. So I ended up instead exporting the shared dependency from the module and having the consumer import it from there, rather than from its own (IIRC otherwise unused and thus eliminated) copy of the shared dependency.
Otherwise this is a great list!
Then code should use != null comparisons which match the none types semantics without needing runtime code generation.
I think this would violate another typescript principles that existing libraries and patterns should be expressable in typescript.
Some schmuck wrote a library that accepts null but not undefined so typescript has to distinguish them.
Unfortunately I feel like every language design team prefers to learn their mistakes on their own instead of learning from others (with the usual “our language is different” excuse).
With codec, one can make sure that the type is correct and defining type and type-guard becomes a one-time task.
> This habit grew I guess because even the official docs use one-letter names. It is also quicker to type and requires less thinking to press T instead of writing a full name.
This habit grew because every language with generics uses such short generic type names and frankly, they are easier to read than MyFancyGenericTypeName.
Thanks for the rest of the article. Pretty good read.
Disagree. Also this same logic can be applied to every other token (ie this argument suggests we should write minified code).
function head<T> (arr: T[]): T | undefined { return arr[0] }
function head<Element> (arr: Element[]): Element | undefined { return arr[0] }
No, it does not. Think of the type variable as a template. The value of this kind of variable does not change during the execution of a function, once given, stays the same. When reading code with generics it does not even make sense to compare the names across two different functions unless they are methods in a class.
Basically, a T in head<T> may be something else than T in tail<T> depending on what the container declares. And what if I use your head<Element> as my head<Leaf>. For me semantically it is not an Element so your forced generic naming is simply going to mess with my brain logic. Leave my T alone. My T is my Type, not some imaginary thing the person who wrote the API imagined I should be putting in there.
This new logic can be applied to every other constant.
> When reading code with generics it does not even make sense to compare the names across two different functions unless they are methods in a class.
Agreed. But I don't think anyone was discussing that.
I find it excellent and definitely a helpful tool to think about when you are struggling with type safety vs runtime data.
I don't think I'll ever be able to convert to using typescript, I'd rather have validators running in the code checking external inputs for the proper fields at runtime before the rest of the system blithely processes whatever it gets due to safe assumptions. Add integration test for specific modules and everything works fine.
I don't want to compile languages that don't need compilation and I don't like the fact that I need to create all of these fake feeling types which are actually just objects rather than javascript classes. It's just feels like boilerplate when you could instead include the 'type' that it's supposed to be in the name and look up a validator for that 'type'.
I'm probably wrong, but it really doesn't feel like it.
It doesn’t obviate the need for dynamic validation nor is it meant to do that. But it does give you a clear point of where to perform those validations rather than littering it everywhere throughout your application.
It doesn’t obviate the need for testing either. But it does eliminate an entire class of dumb programming errors such as incoming a function with the wrong arguments.
TypeScript alone doesn't make any assertions and doesn't offer any checking at system boundaries ("external inputs"). That's not what it is for, and the types you specify with it aren't objects. All that stuff gets compiled out before the code is even run. The point of TypeScript is so that you don't have to run your code to know whether the way it handles data internally is the way you intend it to.
Validation at system boundaries is a separate concern, and handled separately. I like to do it with a package called "runtypes", which both supports arbitrarily complex shapes in its validators, and expresses them in a way that's very close to TS and can be trivially converted into compile-time TS types so that you don't have to write the same types twice.
I wasn't sure what to make of TypeScript for a while, too. But having once tried it, and since become very conversant with it, I'll go back only for trivial tasks or under significant duress. Sure, writing types is a fair bit more work up front and a little more ongoing, but it really does make a huge difference in maintainability; in my experience, it's a little work now to save a lot of work later, as the resulting code is both less likely to exhibit an entire class of often quite subtle bugs, and easier to reason about and modify.
As you've mentioned, integration tests are important, and cover your assumptions on a closer-to-the-user level.
I suspect that there's a flock that prefers working with the testing pyramid remaining standing. Put another way, are uncomfortable if the lower bases are unstable.
There is another flock that prefers the agility and flexibility that comes without logical gymnastics of type checking, relying on inverting the pyramid to prove they're done. Not right or wrong, but another way of making.
Well it's a transpilation, not a compilation, and you are able to run .ts files in dev mode without transpilation.
"fact that I need to create all of these fake feeling types"
I feel the contrary to you. I want everything to be well defined in my application, especially if it's a server :)
Untyped exception in TypeScript is one of the most vulnerable point of static type escapes. Unlike any, which is explicit, exception caught in catch block is implicit.
Personally I prefer to wrap catches into a specific type/symbol `UnknownError { data: unknown }`, and discriminated union to indicate success/failure on return. fp-ts (https://github.com/gcanti/fp-ts) is my go-to library for this
from datetime import datetime
import time
print(datetime.utcnow())
def show_ts(d=datetime.utcnow()):
print(d)
time.sleep(5)
show_ts()
where as in TS, the 2nd one will be roughly 5s older: const now = Date.now();
console.log(now);
function logTs(d=Date.now()) {
console.log(d);
}
setTimeout(()=> {
logTs();
}, 5000); function example(a = 1) {
...
}
behaves the same as function example(a) {
a = (typeof a !== 'undefined') ? a : 1
...
} function test(a = 1) {
console.log(a)
}
test() // -> 1 is printed
test(null) // -> null is printed
test(undefined) // -> 1 is printedYou could have sugar evaluated once, sugar evaluated each time, not-sugar evaluated once, or not-sugar evaluated each time.
If you can find ways to avoid the escape hatches you can then get the compiler to carry more weight and trust in the types without blowback.
edit: read too fast :facepalm:
Anyway great blog post
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
bangbang for life
My pleas, of "just fold the imports in your editor" and "it makes the types globals, so it's not modular" and "interface /declaration merging becomes an issue" all fell on deaf ears.
Some people like their bad habits because it makes sense to them, I guess.
The only one I know of is tslint:
There's a cost to type coupling and over specification