14 ms·
Etsy’s Journey to TypeScript
- pauliusj 5y agoMy only wish is that the compile times were faster. I know typically people will say there's incremental compilation, but I think this problem leaks into many other places. Like vscode suggestions, go to definition, custom build scripts for which you may need to process types etc. I recently had to use eclipse for some java work and it seemed lightning fast in comparison. This is my only (pretty big) complaint about TypeScript, otherwise it's a very useful tool
- koolba 5y agoIf you separate compilation from type checking, the compilation stage is instant. If it’s not, spend the hour or so to understand how to rework your tooling so that it’s working properly. It’ll pay off by the end of the same day.
- aconbere 5y agoI have to admit i’m baffled by this suggestion. I get that compilation and type checking offer different value propositions, but i’ve now walked into a couple of projects that were happily compiling their typescript with babble only to realize once compiling with tsc that there were rampant type errors. I find this idea of throwing away safety for compilation speed to be a non-option.
- k__ 5y agoCould you elaborate? Shouldn't the type checks happen while you write the code?
- dunham 5y agovscode + typescript seems to only surface errors in the current file. If a change breaks something in another file it isn't apparent (in my experience at least). I added tsc to a pre-commit hook to catch these issues.
- k__ 5y agoInteresting. I had the impression it would also include imported files. Thanks! :)
- koolba 5y agoIt’s a perfectly fine option because it’s happening at developer time when you don’t care if it’s wrong. You’re IDE is likely providing typing insights anyway so waiting for the totality of the compilation to see the result of reloading your app isn’t necessary. It’s like using a potentially wrong cache that’s alerts your after the fact that the answer was invalid. Rather than waiting, you proceed to examine the results and likely refine your work before the relatively slow type checker validates the universe. Now if you end up pushing code that hasn’t been type checked then that’s a different story. Might as well run “git yolo” if you’re not going to run type checks, linting or any other sanity tests before indicating you’re own personal sign off of a commit.
- aconbere 5y agoThis just seems like a really long turn around time for type errors. This pushes global type checking into the space of unit testing in terms of time cost. I'd personally much rather have tsc take a second or two and give me the full picture than just hide my eyes until I run unit tests.
- marcinzm 5y agoYour CICD should validate types and lint and fifty other things. The developer when running a local compile does not need to but should before pushing.
- aconbere 5y agoThink about the various tools we have available to us in concentric rings, each with an increasingly longer period. In the inner most ring, the most readily available, happening almost instantly, we have tools like syntax checking, maybe even LSP calls, linting. Time since writing the code is on the order of ms to a second. In the outermost ring, the least available we have CICD, these checks happen rarely, often on a push to a central server. Time since writing the code is on the order of 10s of minutes to potentially hours. I have a really hard time believing that folks are getting so little value out of types, have so few project wide issues, or are so willing to rewrite portions of their work to push type checks into the outer ring of CICD.
- marcinzm 5y agoThat's not what's happening. They're not pushing type checking to the outer ring. They are pushing cli driven gold standard type checking to an intermediate ring and worst case the outer ring. Their IDE can do 95+% of the type checking anyway and only when it fails do they need to escalate. However that escalation is rare and does not need to be done every single time they wish to compile something for local testing.
- pauliusj 5y agoIt's late here, looks like I did a few wording mistakes. The actual compilation (turning ts/tsx into js) is very fast and not a problem at all, what I meant is the typechecking
- lewisl9029 5y agoDecoupling build and typecheck is definitely a good first step, but poor typecheck performance is still going to eventually become a bottleneck in CI as project sizes increase. At Brex we were running up against typecheck times of over 15 minutes at one point before we were forced to address it since it was frequently creeping onto the critical path. We ended up hacking together some CI scripts to share the incremental typecheck cache between builds, which made most checks reasonably fast again (usually well under a minute, averaging 10~ seconds), but there are still frequent large spikes (of 5-15 minutes) in typecheck times on tiny, seemingly innocent changesets (with few dependent files as far as we could tell) that can still really take a toll on productivity. I believe the recommended solution to scale typecheck performance is to break down your app using interdependent project references that serve as atomic units that only get rechecked if they change, but I'm personally not a fan of this approach because most frontend projects don't really derive any intrinsic benefit from this style of organization (as they function perfectly fine as monoliths, and any added indirection only adds unnecessary friction), and project references themselves have a bunch of caveats and introduce a ton more tooling complexity: https://www.typescriptlang.org/docs/handbook/project-references.html#caveats-for-project-references https://www.typescriptlang.org/docs/handbook/project-referen... I wish instead of having to break down our apps into project references manually to reap the performance benefits, TypeScript could just treat each file as a "project" onto itself and give us those performance benefits automatically and by default. In the ideal world I should be able to just run `tsc --noEmit` with the list of files changed from git, and have typescript do the minimum possible amount of work to check all the potential files affected by the changed input files by walking up their dependency graphs, without having to structure my project in a certain way.
- IggleSniggle 5y agoIs what you’re asking for possible? JavaScript can walk both directions on a dependency graph. You can import two things and inject the first dependency into the second. So, unless you want to “structure your project a certain way,” you’re out of luck. If you ARE willing to conform to those patterns then you can get incremental builds. As it happens, you can get something similar within a file by declaring a type interface, telling the compiler “you don’t need to walk the interior of this function because look see here’s the signature,” but you lose the power and dynamism of implicit types / complex generics by doing this. I could be wrong about this; it’s been a minute since ts was my daily driver.
- rpastuszak 5y agoInteresting, I'm generally quite sensitive to small delays when typing/seeing autocomplete, but this hasn't been much of an issue for me, even in VSCode. But maybe that's because I only enable extensions on a per-workspace basis. Regarding build times, have you tried using esbuild (https://esbuild.github.io https://esbuild.github.io)? It's ridiculously fast. vitejs uses it in their dev mode (https://vitejs.dev https://vitejs.dev) if you wanna give it a shot without spending too much time fiddling with configuration.
- remorses 5y agoThe creator of SWC [0] is working on a faster compiler alternative in Rust, so there is still hope for a faster compilation speed in the future [0] https://github.com/swc-project/swc https://github.com/swc-project/swc
- IshKebab 5y agoSWC doesn't do type checking, which means 99% of the work is just stripped type annotations. That's why it's fast.
- christopherbalz 5y agoGreat in-depth write-up!
- bichiliad 5y agoThank you! Very much appreciated.
- deleted 5y ago[deleted]
- Humphrey 5y agoWe've converted most JS projects I work on to TypeScript now, and it is game-changing. Interesting to read how a much larger company did the transition. Main takeaways from this article that I have also found are: - Convert your most imported & core code first - it's much easier to convert files which only have TS imports - so start with those, and work out. - Generating types for API response data has removed so many runtime errors. We generate types from GraphQL schemas. While learning TypeScript takes time (but not much really), now I am familiar with it, I would code faster in TS than in JS.
- mixmastamyk 5y agoDoes TS happen reduce any of the JS (non-type) craziness as well or is it a superset? I'd like a language with one good way to do things that transpiles into JS. Not sure if that is TS or perhaps Dart?
- Humphrey 5y ago> Does TS happen reduce any of the JS (non-type) craziness as well? What craziness are you referring too?
- pacaro 5y agoI have no idea which craziness they were referring to, but one thing that TS doesn't provide (for probably obvious reasons) that could be considered craziness, is an integer type. You're still stuck with the JS number.
- mixmastamyk 5y agoStuff like "===" and "use strict; for non-baffling behavior." Lots more of these kind of things I don't want to think about. I want fewer broken things to avoid. A subset, not a superset.
- pacaro 5y ago
- SavantIdiot 5y ago> All of the above took a week or two Wow, that's crazy fast. Going from JS to TS is a dose of hard reality w.r.t. how many bad patterns JS lets slide. They must have had a lot of devs or a few really good ones. Although I'm surprised they are still using Babel in 2021. I dropped support for it in my FE build flow in 2018 and hit a few corner cases in Europe and China, but that was it.
- Humphrey 5y agoI think the "week or two" was just referring to updating their tool chain to also include support for TypeScript - not actually converting any code.
- sccxy 5y agoIf Babel is outdated in 2021, what is the best practice for FE build flow? I'm thinking about updating my projects but there too many options to choose from..
- SavantIdiot 5y agoWe use the JS outputted by TSC in both webpack and nuxt projects. I honestly don't know if that is bad, but I have such a small team that no one really knows. We're not Etsy-sized. :) This article drove it: https://blog.logrocket.com/why-you-dont-need-babel/ https://blog.logrocket.com/why-you-dont-need-babel/ EDIT: Plus we also wanted to go on a package diet because we found ourselves doing too much cut-and-paste from github w/o really knowing how to use all the tools.
- WorldMaker 5y agoThe number of transforms that Babel is doing with an "evergreen" config ("last 2 browser versions") at this point is effectively miniscule. It's a massive toolchain for what increasing turns out to be a minimal amount of actual work. "Last 2 Browser Versions" is effectively everything through ES2019 at this point which covers almost all of the "modern JS syntax". If you aren't using custom transforms you might not be transforming anything that matters in Babel in 2021. I've seen a bunch of projects with huge Babel pipelines where the only actual transform was Typescript's type removal and at that point, if your codebase is entirely Typescript, Typescript has all the downlevel transforms you need "baked in" (and arguably a little bit cleaner and simpler to Babel's kitchen sink but also still somehow millions of plugins approach) and it's just setting Typescript's compile option to the ES level you are most comfortable with. (In 2021 that may even be as high as { "target": "es2019" } or higher in your tsconfig.json and even there Typescript's not going to even need to downlevel much.) Typescript can also transform TSX/JSX to JS without the need of Babel, if you are using React. Even ES2015 modules which some people still think is the big reason to keep Babel around: a) has full Browser support if you use type="module", but most people still want to pack their JS because just about no one is assuming HTTP/2 or HTTP/3 yet, and b) Babel has never done module format transforms, that's always been the domain of your packer (webpack, parcel, rollup, snowpack, what have you). If you are updating your project stack in 2021 right now my personal top recommendation is that I really like the approach of snowpack (https://www.snowpack.dev/ https://www.snowpack.dev/): ES2105 modules with <script type="module"> dev experience (which is great), great Typescript support, and a simpler overall config experience than most other options right now. (It uses esbuild under the hood rather than babel for dev and basic transforms/bundling. It can optionally piggy back webpack and parcel for Production bundling that needs more "power".) Especially that <script type='module"> dev experience feels great now (with Hot Module Reloading too) versus waiting for a full bundle even for dev builds.
- byhemechi 5y agoTypeScript is one of those things that doesn't feel like it's doing much when you start working with it but then when you try to switch back to writing vanilla JS you wonder how you ever managed. The editor tooling alone makes it easily worth the setup time.
- throwaway894345 5y agoThis may be the perspective of a JS veteran (who has the types of common APIs committed to memory), but I keep a respectful distance from JS and only seriously touched TS yesterday and already the benefits seem significant.
- zdragnar 5y agoAs a JS veteran, it took me a long time to come around to TypeScript. Early on, there was a lot that was missing from it and a lot of libraries weren't really terribly pleasant to use with it, especially if you're using something like angularjs or Ember with its own DSL for templates that isn't TS aware. You really got accustomed to either memorizing the types of things, or remembering how to look them up very quickly. But, two things have happened. My once sharp-as-a-japenese-knife memory feels a bit more like safety scissors nowadays, and the type system has added such fantastic support for useful features - unions, enums and the lot keep getting better with every release. Generics, mapped types and advanced types get really close to being able to fully describe the full expressive power of JavaScript. I dove in head first a few years back, and have only a few small quibbles over what it can and cannot express, or how easy it is to do so. With all of that said, it can be really hard to sell JS veterans on TS. Intellisense in webstorm and the like can be quite powerful, especially if they drank the JSDoc kool-aid, so it can be tough to really clearly spell out the advantages since their tooling mimics a type system already.
- capableweb 5y ago> With all of that said, it can be really hard to sell JS veterans on TS. Intellisense in webstorm and the like can be quite powerful, especially if they drank the JSDoc kool-aid, so it can be tough to really clearly spell out the advantages since their tooling mimics a type system already. As someone who is not sold on TS and writes JS every day, what advantages does TS provide over JSDoc? Both are just valid during compile/build/transpile time, so they seem mostly the same, except one is built and pushed by a huge company that has a history of supressing open source, while the other one is built by the community for the community.
- peanut_worm 5y agoLearning Typescript was probably one of the best investments of time I have ever made. It took like 3 hours to learn all together and saved me at least 20 hours of debugging already.
- azangru 5y ago> It took like 3 hours to learn all together Me, raising an incredulous eyebrow.
- peanut_worm 5y agoSorry, not to learn entirely but to learn more than enough to benefit from it greatly.
- schwartzworld 5y agoThey already knew JS.
- azangru 5y agoStill. Generics. `extends` with ternaries. `infer` within conditional types. Type narrowing. Lots of the language quirks.
- pietrovismara 5y agoThis is correct. I feel there are 2 distinct levels of knowledge with Typescript: the application level and the library level. The application level is fairly easy, but if you want to write libraries with good types you're going to have to dive in the more complex features of Typescript. Still not rocket science, but it takes way more than 3 hours, even if one studies it intensively.
- afavour 5y agoIt’s probably better to say 3 hours to learn enough to start coding a project. If you already know JS I really think you could learn 80% of TypeScript in three hours. But the last 20% would take a long time: generics, union types, that sort of stuff.
- vosper 5y agoTypescript is the language that will put a lot of other server-side-only languages to bed when it comes to web-application back-ends (and then it will seep into everything else, unless it's performance critical, but at some point that'll probably be addressed, too).
- Scarbutt 5y agoSad but true.
- jmath 5y agoi sure wouldn’t mind seeing typescript become a dominant language in back-end development
- RhodesianHunter 5y agoPeople who've been writing only JS for years descover typing and suddenly think it's the holy grail.
- jamil7 5y agoYeah while they liberally apply ‘any’ all over a codebase.
- exdsq 5y agoI’ve just accepted this is true (for JS or TS). I spent years avoiding using JS but have just come to accept I need to crack on with it regardless, it’s here to stay and probably just going to grow. No point severely harming my job options over technical preferences.
- valenterry 5y agoI don't think so. Typescript is a decent language, but severely suffers from the javascript compatibity. On the frontend that does not matter as much because you usually don't deal with critical data persistence, but on the backend it's different. If what you said was true, Javascript would have already taken over the backend, but it hasn't. There are two reasons why: 1. There are still languages on the backend that are more productive / powerful / mature than typescript. 2. On the frontend side, the hurdle of getting into things is much lower. That's why, on average, folks working on the backend are usually more involved and have a broader exposure the languages. That being said, there are surely languages, I would love to see replaced by Typescript (for example looking at you, Java). And while it might look like Typescript could do it from someone who uses it for frontend, I'd say it won't happen.
- intellix 5y agoI really don't understand how the dinosaurs see things. You can be using something for 5 years and see the benefits before you're reading an article about how X company started using and benefiting from it. Can't wait to be reading in 5 years how Graphql was better for a company using SOAP
- MrPatan 5y agoBecause they were busy making money instead of worrying about the tech.
- bichiliad 5y agoHey gang, I'm the author of this post! Very excited to see it show up on HN. I'm currently on Paris time (finally got some vacation in) but I'm happy to answer any questions you all might have about the article, our transition, and even TypeScript in general (although there are plenty of other smart folks that might have better answers than me on that last one).
- acemarke 5y agoI saw in https://codeascraft.com/2021/11/04/mobius-adopting-jsx-while-prioritizing-user-experience/ https://codeascraft.com/2021/11/04/mobius-adopting-jsx-while... that you're using Redux Toolkit (which I created and maintain). I'm curious if you have any thoughts on using RTK in general and RTK+TS specifically.
- bichiliad 5y agoHonestly, RTK made migrating our existing Redux code to TS so much easier. I really can't thank you enough. We often had teams adopt RTK (in favor of some internal Redux-based helper methods) before helping them migrate other files. In particular, the createAction `.match` pattern made adding types to our actin really simple. I think the only thing that felt awkward was using the ThunkAPI generic when we needed to access state in, say, `createAsyncThunk`, but even that wasn't all that bad after we got used to the pattern. I'm happy to provide more specific feedback if you'd like (hi@salem.io).
- acemarke 5y agoAwesome, glad to hear that's working out well! You can thank Lenz Weber ( @phryneas on Github ) for much of that API design, both the APIs themselves and the TS typing. Yeah, let's just say that `createAsyncThunk`'s use of TS generics is, uh.... interesting :) The "object field override" generic technique is neat, but also weird at the same time. Really, just doing `const state = thunkApi.getState() as RootState` is an entirely valid workaround here. Sure, you can argue it's not as "type-safe", but it's got the same net result and it's less clunky. Just out of curiosity, has anyone looked at our new RTK Query data fetching API for possible usage? The reception for RTKQ has been highly enthusiastic so far, and it's designed to eliminate the need to write _any_ thunks or reducers for data caching scenarios. (Like everything else Redux, you can mix and match whichever works best for a given use case.) - https://redux-toolkit.js.org/rtk-query/overview https://redux-toolkit.js.org/rtk-query/overview - https://redux.js.org/tutorials/essentials/part-7-rtk-query-basics https://redux.js.org/tutorials/essentials/part-7-rtk-query-b...
- cryptica 5y agoThe real purpose of TypeScript is job creation. Corporations constantly need new ways to keep their employees busy, distracted, and compliant. I really hope that one day, most developers will realize that there are far more important things than static typing... I mean so much more important that it makes static typing seem completely futile and even counterproductive. You may downvote today, but you might understand what I mean in 5 to 10 years. I've been through all the phases already. I'm even exhausted trying to explain it to people. The hype is too strong. Good luck, gen z.
- girvo 5y agoI'll downvote today because cryptic "you'll understand when you're older" comments that don't expand on why you believe that to be the case add very little to the discourse, even if I might agree with the overall premise.
- throwanem 5y agoIf you've been to that much effort already, one imagines you'll have a canned summary of your thesis and arguments somewhere linkable. I mean, of course there are far more important things than static typing. Which of them do you have in mind?
- Scarbutt 5y agoHandling of state. Reusability, extendability, flexibility, immutability, avoiding brittleness and coupling. The things Typescript gives you are very physically visible and so, gives the illusion and confidence it will guard you in everything but in reality it helps in the most trivial of problems and you are paying a big cost for it.
- mb7733 5y agoWhat is the cost?
- throwanem 5y agoI've been writing Javascript for twenty-six years, seventeen professionally, and Typescript since 2017. No one has ever in my experience made the claim that Typescript solves all, or even really any, of the concerns you list. That when well used it can make them easier to solve, sure, and that's true. It comes in exchange for a little more effort, that's also true, but I've found that tradeoff considerably beneficial on net, because the type system when used thoughtfully makes whole classes of bugs harder to write, and their virtuous complements easier. If people are saying the type system is a magic bullet, the problem is with that claim and the people making it, not with the type system.
- wpietri 5y agoCan anybody who has done both compare TypeScript's gradual typing with Python's?
- MapleWalnut 5y agoThey're pretty similar. The auto complete alone is worth adding type annotations. Both have type stubs for third party packages that can make it easier to get coverage for your project. My organization gradually migrated a ~300k line Python project to have full type annotations and it's so much nicer to work on.
- sizediterable 5y agoMost of my experience is with mypy and TypeScript. If your Python code relies a lot on dynamic dict objects instead of classes you'll have a rougher time. You have to use `TypedDict` which is not very expressive and syntactically verbose. This could be considered a good thing since you'll be pushed to use things like `NamedTuple`, `dataclass`es, or (a third-party extension) `attrs`. Most JS/TS code is probably using plain objects rather than `Map`s. The TypeScript syntax for expressing object types is extremely expressive, though annoyingly `Object.keys` and `Object.entries` are not precisely typed (For legitimate soundness reasons. Object types are "inexact", whereas in Flow you can express both "exact" and "inexact".) mypy supports union types, but not intersection types, unlike TypeScript. The closest you can get is creating a `Protocol` (i.e. interface) that extends multiple `Protocol`s, but this can be cumbersome. mypy's generics are strictly worse, both syntactically and expressively. In mypy you can express both co/contra-variance explicitly, whereas in TypeScript variance is implied by the readonly-ness of an object's properties and variance of its methods. Both mypy and TypeScript have `Any`/`any` types, but only TypeScript has the safer `unknown` type. You can kind of use `object` in mypy for this purpose. Both have a "bottom" type, "NoReturn" and "never", respectively. mypy has decent support for classes and subclass type-checking. TypeScript doesn't truly understand sub-class relationships nor even prototypal inheritance. Both are very configurable in terms of the strictness checks, but mypy's flags are more poorly documented and it requires more work to increase the level of strictness. Enabling "strict" in TypeScript enables most of what one would want. Anecdotally, I would say TypeScript has better control flow analysis. With mypy you have to cast a lot more often. The TypeScript ecosystem is much stronger. Most new packages have types as do major packages (located in DefinitelyTyped repo). Python's typing ecosystem is fairly poor. There are barely any packages in Typeshed and a lot of new packages are still untyped. TypeScript has a dedicated team at Microsoft working on it with a public roadmap and milestones, though big features only come around one or twice a year. Python's type ecosystem is more design by committee. A lot of conversation happens over mailing lists, monthly video calls, and a yearly conference. Since there are multiple Python type checker implementations, there isn't a single unifying vision. The core mypy team is employed by Dropbox, who has them spending most of the time migrating the giant monorepo from Python 2 to Python 3. The TypeScript team is fairly decent at fixing true bugs between releases, but a lot of "bugs" are really feature requests that tend to become long-standing Github issues. On the other hand, last I checked, there are still some long-standing bugs in mypy that haven't been fixed (as not to spread FUD, I will say that they tend to be very edge-casey and more for power users). Note that there are multiple type checkers for Python at this point with varying capabilities, but they share the same syntax and basic types since they're built into the language runtime. I expect Pyright (also from Microsoft) to come out ahead as more people start using the Pylance VSCode extension. mypy's editor/IDE support is not great, based on my VSCode experience. I haven't tried it with PyCharm.
- tacotacotaco 5y agoTypes don't make you write better code. In my opinion TS makes writing bad code easier because intellisense. Every TS project I have worked on is as messy as the JS projects. I have nothing against type systems. I have years of experience with C, C++, and Java. However, I happen to think functional programming is a lot more "game-changing" and TS makes writing functional code more difficult. But hey... types are enterprise so it must be good. I would truly appreciate it if our industry would dedicate more time to training both new and senior devs to write better code instead of chasing the every popular/new language/framework/build-tool that promises to solve all the things.
- smt88 5y agoYour argument against TS is that it makes writing correct code easier? There is no situation where better autocomplete and compiler errors make code worse. Coding should be as easy as possible, and footguns should be almost impossible to introduce. I've been writing code for 20 years, and TS is the first language I used where I would often find 0 runtime errors in my first version of a project. It takes discipline to achieve that, but TS helps with discipline by saving you the overhead of all the other JS nonsense.
- seer 5y agoI think I also agree that TS has made js programs harder, but not in a bad way. You see there was a quote back in the day about a discussion between a senior clojure developer and a java one, and it went something like this. Java dev - “How do you know when you refactor your app that if you change something in one place, it will not cause a problem in another distant part of the app, without the compiler to help you” And the clojure dev answers with “why would you ever write an app where one thing in one place changes another thing in another place?” I forgot where it was from though. Anyway the sentiment is that clojure gives you tools to write an app like that where all the things that affect each other are close by, so it is actually possible to write big apps without types. TS on the other hand gives you tools to write a big app where things _can_ affect different places, but you can still manage it. You can “fit” a bigger app in your brain. JS by itself gives you no tools whatsoever so you’re at your own mercy, so you’re either more careful, or don’t write big programs and stay small. Or alternatively invent strategies that help organize things (redux, express, react). TS allows you to ignore all that, write a horrible mess, and still be able to ship and be productive. It makes bigger messes actually possible. Now I’m a huuuge fan of TS myself and never start a frontend project without it. And I also think it can make code, especially functional code much better and easier to reason about. But we’ve lost the natural selection of JS projects. Before TS, if you’ve not setup your project right, with test, structure, policies and processes it was doomed the moment it grew to a certain size. You either stayed small, did it right or failed and refactored. Now … now you can actually keep going for much much longer with just TS helping you. And god forbid the TS wiz that sets it all up leaves and you’re left with untangling a mess. It’s a nicer mess, but a bigger one.
- globalise83 5y agoI love using Typescript, but I only ever use interface and enum. What extra benefits would I get from using other features than those? What am I missing out on? :)
- rpastuszak 5y agoIMO you should ditch enums (just use union types 'value1' | 'value2' etc...) and stick to writing "statically typed javascript". You'll get enough value from it. Incomplete and (very) biased list of why I find this approach useful: - Amazing static analysis capabilities - Being able to design the code by writing types first and just filling the gaps between them - Less code which needs to be covered with unit tests - Autocomplete for any 3rd party library (e.g. AWS, or try spiking some backend code with Contentful and navigating their data structures, it's sooo much easier once you describe your models using TS) - Less thinking about "how" and more about "what" I want to build - Still reads like JS so the barrier of entry for colleagues is easy I'm not a big fan of interfaces, but I understand why they exist (declaration merging/patching mutable JS scopes/objects). Edit: I just realised that I got overly excited and perhaps went too broad with the list of pros, but hope this is still useful. The official TS documentation says that you should default to interfaces instead of types, but the approach that worked really well for me is to start with types and use interfaces only when really necessary. Somehow this model fits better in my head, but that's maybe because my coding style is more functional than OOP.
- gherkinnn 5y agoTagged union types [0] are very powerful and let you model most things in very robust ways. type Response<Data, Error = string> = | { type: "Loading" } | { type: "Success", data: Data } | { type: "Error", message: Error } You won't have access to data unless type === "Success". You can model other mutually exclusive situations in the same way. Then, Typescript comes with very handy utility types. [1] And if you're having an especially good day, you can loose yourself in type level programming. Mapped types, for example. [2] Though this is only really necessary at a library level. Back in reality, type narrowing [3] and function overloading [4] are good to know about. And there's a lot more. - 0 https://mariusschulz.com/blog/tagged-union-types-in-typescript https://mariusschulz.com/blog/tagged-union-types-in-typescri... - 1 https://www.typescriptlang.org/docs/handbook/utility-types.html https://www.typescriptlang.org/docs/handbook/utility-types.h... - 2 https://www.typescriptlang.org/docs/handbook/2/mapped-types.html https://www.typescriptlang.org/docs/handbook/2/mapped-types.... - 3 https://www.typescriptlang.org/docs/handbook/2/narrowing.html https://www.typescriptlang.org/docs/handbook/2/narrowing.htm... - 4 https://www.typescriptlang.org/docs/handbook/2/functions.html#function-overloads https://www.typescriptlang.org/docs/handbook/2/functions.htm...
- hoofhearted 5y agoTypescript… Hated it as first. But once I realized it was for writing JavaScript with a C# flavor, I don’t think we could go back. The only thing that makes me scratch me head about TS is that you declare your types backwards compared to C#. Ex. value:string vs. string value. Is there any good reason for why Microsoft did that? Or can that be updated so a C# developer can jump into Typescript and write TS and TSX components with less friction?
- moogly 5y agoNot an authority on the subject, but on the implementation side I guess it simplifies parsing and "type erasure" (I don't know the proper terminology for transpilation). As for developer experience, I'm sure it helps gradual typing. I much prefer that style since it doesn't keep pushing the most important names to the right and causing jagged textual structure (never knowing at which column function/method names begin, unless you go with a multiline declaration style, which some C/C++ shops do). At this point I wish all languages with a C origin used name-focused as opposed to type or qualifier-focused style, but you can't really change it now.