Vinnl 4 years ago

It's really telling that, for every big project that does not support TypeScript, the number 1 feature request is TypeScript support. (And consequently, that there are fewer and fewer such projects.)

  • joshstrange 4 years ago

    I won't pretend tsconfig/webpack or any other bundler out there is "fun" to work with but once I get my TS support working in a project it is a joy to write in TS. I already liked JS (if that didn't make you hate me I like PHP too and have gotten paid to write it for a decade now) but TS really pushed me over the top.

    I avoided TS like the plague because I didn't want another layer added in and I thought it was just coffeescript++ but after taking the plunge on 6to5 (renamed to babel) because "well these features are coming to JS soon anyway or have already landed in stable browsers" it was just a hop, skip, and a jump over into TS (in for a penny...). Modern JS is actually really fun to work in and TS takes to the next level with peace of mind I never had with just JS.

    • ewired 4 years ago

      > I won't pretend tsconfig/webpack or any other bundler out there is "fun" to work with

      For me, Parcel is fun to work with. Rollup is my favorite for more advanced or customized pipelines, but Parcel has a silky smooth workflow for the typical bundling tasks in most projects. I've started using it for Node.js as well (since I want to avoid ts-node) but it seems best for frontend-only projects and components. Speaking as someone who has managed to avoid Webpack thus far despite its status as the "industry standard".

      • sunsetSamurai 4 years ago

        do you have any guide on how to setup,TS, linters etc with Parcel?

        • zamalek 4 years ago

          The whole point of Parcel is that you basically can't configure it. TS should just work.

          Rollup is basically a configurable Parcel.

          • esperent 4 years ago

            Look into esbuild as well. It falls somewhere in between Parcel and Rollup in terms of configuration options but it's way faster (around 10x compared to Rollup for my tests) than either.

          • hardwaresofton 4 years ago

            last time I tried to use Rollup, I found that it was very focused on NodeJS libs rather than frontend projects where Webpack (or other tools that bill themselves as "bundlers") is used more often. After a few "oh, rollup doesn't do that by default, guess I need this plugin"-situations, I switched back to Parcel.

            Has that changed? Was I just not using it right or didn't read the right rollup-for-the-web documentation?

            • tehbeard 4 years ago

              Rollup isn't focused on node, if it was commonJS support would be bundled into the code.

              It's got a small and focused core that aims for esm (I regard the other output formats supported as esm -> that format).

              You do need to plug stuff in rather than having a batteries included experience. But that is a strength imo where you want to worry only about what you need.

              I do recommend adapting an existing config when using it in a new project, or creating your own templates/"create-x-app" wrapper.

              I use it for my home projects, and several work ones. It's "lower level" than Babel or parcel but that means I can set it up to compile both a lean, modern esm build, and a legacy IE11 compatible polyfilled systemJS bundle much easier than I can in webpack with its proprietary bundle format or parcels zero config.

              I will admit that node resolve and commonJs rollup plugins are pretty much a required part to work within the npm ecosystem right now, so it is a bit more boilerplate-y than I'd like.

              • hardwaresofton 4 years ago

                Thanks for noting this -- I ought to give it another try in the near future.

            • zamalek 4 years ago

              I use NodeJS exclusively for running Rollup (I'm using Rust for the back-end), and I use Rollup exclusively for the front-end bundling (TS, SCSS, Babel, SVGO, minifiers).

              Have a look at the Svelte templates, they all use Rollup. Configuring Rollup is far more straightforward than Webpack and source maps just work. I'm pretty sure you'll like it.

              • hardwaresofton 4 years ago

                I need to give it another try -- I end up separating my front and backend codebases completely so while I don't have to worry about mixing, I did find that Rollup was more complicated than Parcel so I just went with Parcel.

                Out of curiosity, what are you using as your HTTP server library/framework for Rust? At this point I've used a bunch of them (maybe 3/6+ that are out there) and am curious what others are using.

                • zamalek 4 years ago

                  What I've tried for this project (in chronological order):

                  * Gotham. Pros: very clean. Cons: lots of boilerplate code.

                  * Actix-web: Pros: very little happy-path boilerplate code. Fastest framework right now. Cons: error handling is just awful - I struggled to get `?` to work. Glacial compilation times.

                  * Rocket (0.5 direct Git dependency). Pros: route handlers almost entirely consist of logic I care about, even for errors. Feels very deliberately "rusty." Cons: no HTTP2. No websockets. It has been accused of being "too magic."

                  Each resulted in a ~20% reduction in LOC. I tend toward getting shit done, so I'm over the moon with Rocket.

                  • hardwaresofton 4 years ago

                    Thanks for sharing -- for me:

                    * actix-web:

                      Pros: good docs, well supported, good eco system, Actor model fits very well with how I build systems (Actor ~= Component)
                    
                      Cons: some ceremony around setup of the app object
                    
                    * tower-web

                      Pros: good ergonomics, much easier to wrangle app state
                    
                      Cons: all-in-one macro is a bit hard to reason about, hard to split up bits of API (I might have just not known enough about how to break up the impl_web! macro)
                    
                    * warp Pros: express-y (req, resp) => result interface, surprisingly feature complete (http2, sse, websockets) due to building off of simple interfaces/extension points, functional APIs that are easy to compose

                      Cons: very new, kind of experimental, docs are a little lacking but examples help
            • tazard 4 years ago

              That hasn't been my experience at all, in fact recent tools such as vite and snowpack are built on using rollup for frontend projects. You do need to install the plugins you want to use as they aren't all available out of the box, but generally I haven't had any troubles and basically just stick to the official plugins.

        • ewired 4 years ago

          From what I can tell, Parcel v1 does not have linting, but I rely on linting and typechecking in my editor anyway, so I didn't notice. It's actually pretty handy to bypass typechecking and write untyped JS to quickly check if something will work then add types to it gradually. VS Code yells at me until I fix it, so it doesn't go unfixed.

          https://parceljs.org/ is the homepage. Run the command (or put the command in an npm script) like `parcel whatever.ts` and it will output your bundle with all dependencies transpiled to JS and CSS. The simplicity does come at a cost; it's not as readily customizable as something like Rollup. I've been eagerly tracking v2 and it appears they are adding linting and much more into Parcel.

          • kangabru 4 years ago

            Yeah I had the same issue and have been following the Typescript thread on GH for a while now [1]. But I agree, I actually like using untyped JS for development.

            What I do now is throw a "tsc --noEmit" call before tests/prod build to type everything before parcel runs. Works well enough.

            [1] https://github.com/parcel-bundler/parcel/issues/4022

  • moltar 4 years ago

    I basically haven’t written any JS code in over two years at this point. Everything I do is TypeScript. When I pick libraries I make sure they have TypeScript support. Preference goes to TypeScript-written packages.

    • koolba 4 years ago

      > Preference goes to TypeScript-written packages.

      Indeed, the only thing worse than no typings is wrong typings.

      • joshstrange 4 years ago

        Those 2-4 seconds when you type `npm i @types/packageName` and hope you don't get a 404 or worse it comes down but hasn't been updated in forever.

  • pjmlp 4 years ago

    Because it comes down to what I advocate, guest languages only look nicer on the surface, they add up more layers to debug, extra tooling to integrate, FFI to platform and library wrappers for idiomatic code.

    Since the Web platform isn't going away from JavaScript anytime soon, and WebAssembly is relatively constrained beyond WebGL, that leaves UI frameworks as the possible "platform".

    What I am looking for is that the adoption will keep carrying on, to the point that browser natively understand Typescript, or WebIDL for that matter.

    • Vinnl 4 years ago

      Browsers don't need to understand TypeScript, but just be able to ignore TS-specific syntax like Babel does. Then it's really possible to use TypeScript like a linter without requiring a bundler.

      But of course, that'll add quite a drag on TypeScript development. With Babel, they can just maintain the plugin themselves; with browsers, they'll have to go through the standardisation track for every syntax change they want to make.

      • pjmlp 4 years ago

        Strong typing is not only about linting, JSLint already does that.

        TypeScript also has to go through the same process, after all they need to grow alongside JavaScript and besides typing, there is nothing that gets introduced that isn't JavaScript at its core.

        • Vinnl 4 years ago

          Sure, but the value of TypeScript is that it warns you about bugs in your editor or at compile time. The value of browsers supporting TypeScript would be that you can serve it up to users without a build step.

          • pjmlp 4 years ago

            My IDE already does that for JavaScript as well, the benefit of strong typing on the browser, besides removing the build step, is that JIT would be able to actually take advantage of the type system instead of guessing and hoping for the best.

  • swyx 4 years ago

    indeed we are in a new age of javascript now. one where TS support is (in practice) not optional. https://www.swyx.io/writing/js-third-age/

    • novok 4 years ago

      Might as well make it part of the language officially and get rid of the need for transcompliers.

      • mekster 4 years ago

        Not going to happen anytime soon as people will take forever to upgrade to browsers that may support TS natively.

        Stick with transpilers and you're good to go from today.

        There's also deno for node.js alternative that supports TS natively but not sure of its future.

      • kylemh 4 years ago

        laughs in browser compat

    • hajile 4 years ago

      We really need a "use types" mode.

      Instead of trying to support all the super-dynamic parts of JS, those parts should just go away in typed mode. Unlike TS, the type system should be sound. Hindley-Milner with immutable by default and options instead of null with structural typing everywhere and typeclass module definitions.

      I guess that's just StandardML with JS syntax, but that would be an amazing language to work with -- far better than either TS or ReasonML.

      • still_grokking 4 years ago

        ReasonML is ML (OCaml) with JS syntax. OCaml has more features than SML. So I'm not sure what you're after.

        And regarding "the dynamic parts should just go away": No, please! And I'm saying this as a full time Scala dev doing "pure FP" in my day job who loves static types. But I also really like the "super-dynamic" parts of JS. I think such features should get integrated into some static lang. This would need some thinking though. The "old" static languages can't do that easily. To bring an example of what I mean: One can see JS objects as "extensible records". Adding and removing props on a prototype looks for example like "a super-dynamic" feature. But "extensible records" are also doable in static langs. I think more of those "super-dynamic" features are actually doable in a static context. Extending current FP languages with all kind of such features would be quite desirable, imho. "Why not have both?" :-)

  • tester756 4 years ago

    I think that's just proof that "the next future" of web development is going to be owned by languages like C# (that __already__ allow you to write decent client side web apps) and other already popular not dynamic languages

    After C# of course yet another DSLs.

    • rubber_duck 4 years ago

      I came to TS after years of C#, all the way back to .NET 2.0 and WinForms.

      TBH TypeScript is just better than C# for the job it does - DOM control and gluing data - structural typing that's backed by a dynamic runtime is a much better fit for those kinds of tasks than a nominal type system backed by IL level type checking - AutoMapper is nonsense created by this design decision and C# is particularly verbose (almost Java level).

      C# allows you to get much lower level than TS can, you can control memory layout, allocation patterns, you have proper threading model, etc. etc.

      But for dealing with single threaded DOM event loop, stitching data from all kinds of sources, simple transformations and sending it around - IMO TS is a better fit.

    • cageface 4 years ago

      Typescript can seamlessly interop with existing JS libraries. This is a huge advantage over any non-JS language.

      • tester756 4 years ago

        Ain't everything going to be WASM anyway?

    • k__ 4 years ago

      I hope not.

      C# is too bloated for my taste and I have to admit, TS is too close to C# for my taste.

      • Vinnl 4 years ago

        If it's like C# in that it's bloated, I can see why you might say that, but I'm quite sure that my TS code looks nothing like C# code. (Because it's almost exactly like my JS code, but with annotations and fewer redundant checks.)

        • k__ 4 years ago

          To me, C# like type annotations, especially generics, look bloated.

          ReasonML files don't look like that and are even sound.

      • tester756 4 years ago

        I do agree that it's becoming lately

wry_discontent 4 years ago

I feel like the odd man out in discussions like these. I don't like Typescript and I regret pushing to integrate it into a project at work.

I've found it vastly increases incidental complexity and affords little to no benefit to me. The IDE completions are nice, but ultimately not worth the price, in my humble and honest opinion.

  • cageface 4 years ago

    After working in Typescript for 18 months I've moved onto a new Rails project and I miss type checking so much every single day. There are so many dumb bugs that have slipped their way into production that would have been caught by type checks and null checks. It's professionally embarrassing for the client to see this stuff that would have been stopped by better tools.

    • genuine_smiles 4 years ago

      Have you looked at Sorbet?

      https://sorbet.org/

      • cageface 4 years ago

        Yeah I tried using this on our current project but it couldn't really handle Rails + all the gems we're using. I think it's very difficult to retrofit types onto a codebase with deep roots in dynamic code.

        • mekster 4 years ago

          Just hope ruby 3 would integrate static typing.

  • qudat 4 years ago

    The real benefit is with refactoring. It is built-in testing. If I change an interface because a business requirement changed, I immediately follow a trail of errors that I need to fix. If types are setup properly, making major changes is dramatically simpler to accomplish.

  • keb_ 4 years ago

    I also disliked my time with TypeScript, but perhaps its value hasn't made itself entirely apparent to me. Most of my programming experience has also been with dynamically typed languages. I think if you had already spent enough time with a language like JavaScript or Lua and familiarized yourself with its quirks/footguns, you learn how to avoid the common pitfalls of not having a strict type system.

    Although I've found that TypeScript is a great way to attract devs who hate JavaScript to try working on front-end.

    • cageface 4 years ago

      When working with devs that have grown up on dynamically typed languages I often find that they have not really thought carefully about the structure of their data and there are essentially many ad hoc data types strewn throughout the code. Thinking in types from the beginning leads to much better structured code and stronger abstractions IMO.

      • DabbyDabberson 4 years ago

        I couldn't agree more. I think the introduction of types in JS (either TS or flow) has been the single biggest leap in front end development in a decade.

      • wry_discontent 4 years ago

        I see the same thing, but in people who primarily work in statically typed languages. I don't think there's much of a pattern in wrt types, but people who don't think about data.

        • cageface 4 years ago

          Specifying all those complex ad hoc data types in a statically typed language is so tedious I think it pushes you to start looking for unifying abstractions.

    • mekster 4 years ago

      What editor are you using? If you don't use an editor that supports TS, then it's all moot.

      Editors are meant to auto complete any parameters that you have typed as well as provide errors that don't fit to your typing.

      Using editors like vim wouldn't work.

      • brlewis 4 years ago

        > Using editors like vim wouldn't work

        Hi. Fellow emacs enthusiast here. We can evangelize emacs tide mode and slander vim on other TypeScript articles, but I think it's best not to do so on this article, because it specifically mentions vim in the editor support section.

        https://svelte.dev/blog/svelte-and-typescript#2_Editor_Suppo...

      • keb_ 4 years ago

        Hey, I used VSCode. I could see how tightly integrated TS was with it, and I appreciated it.

  • ipnon 4 years ago

    How large is your TypeScript project? What were your type issues before you integrated?

    My work has benefited from TypeScript because we can now propagate changes to our unstable API throughout our medium sized application using the compiler. We are fairly certain that all of our components are integrated if the compiler is silent. Before this certainty, we would frequently push broken API integrations to production.

    The complexity of TypeScript doesn't seem to benefit projects that are already clean and tested. TypeScript gave us some confidence of correctness when we had disorganized code and inadequate test coverage.

    • wry_discontent 4 years ago

      It's about 20kloc.

      I encounter seemingly nonstop opaque type errors that come usually when I upgrade TS versions. I'll stipulate this was mostly written when we decided to add TS, and I was new to TS when I added it, but I tried really hard.

      As an example, it took me a full week to properly add type definitions to a HOC, and I had to rope in a couple other engineers across that time who had more TS experience. Eventually I got it working, but decided to deprecate the HOC cause the file exploded from being about 50loc to well over 250.

      • treve 4 years ago

        The last large project I added Typescript, it took several weeks to add types. It took another year to learn how to write code in a way that is more likely to be successful in Typescript.

        If you have a ton of state, classes, high coupling and a lot of variance in your data structures (which Javascript really easily allows), Typescript is not an instant game-changer.

        This is not that different from having good test coverage is easier during development than adding it later, as you will end up writing your code in a way that makes things more decoupled and testable.

        It was way easier to get to that sweet spot with our Node.js code vs. our React code. React code is still more of a battle than non-React code, although functional components has made this better. Class based components suck the most and we just opt for using "any" instead of fighting it. Don't get me started about HoC.

  • camgunz 4 years ago

    Yeah by the numbers I like it (sum types!), but what put me off is in practice, TS is built for autocomplete. If you aren’t using that, it’s a real pain to guess what type you need to say, and you’re basically digging through code or bad/old docs to find out.

    I also found the typing to not really help. Non-null stuff is nice, but without range types, I don’t think the trade off is worth it. It helps about as much as Go’s type system but asks you to do 3x the work, restrict yourself to typed libraries, and setup some pretty tricky tooling.

  • orange8 4 years ago

    TS was designed to solve a problem. If you cannot see the problem, then you do not need it. Unless when working in teams with devs more used to thinking and structuring their code around types.

    • mekster 4 years ago

      Actually TS shows you the problem when you hadn't realized.

      Use it with a proper editor that supports TS like VS code or IntelliJ and figure it out.

      • orange8 4 years ago

        I have used TS before, and VS Code is the best editor. I simply do not have a problem with JS, or dynamic languages for that matter.

  • schwartzworld 4 years ago

    HN has a high proportion of experienced programmers coming from typed languages. If you are a C# dev who has to write JS, I'm sure typescript is a breath of fresh air, but from where I stand it's awful. The whole point of TS is to reduce the friction in writing JS for those people.

    However, from where I stand, Typescript sucks. Sucks sucks sucks. It takes everything I love about JS programming and turns it into suck.

vosper 4 years ago

Lack of Typescript support was the main reason I didn't switch to Svelte for my personal projects. Other than that it was a joy to use, and a breath of fresh air in it's approach.

I'd recommend any front-end dev to give Svelte a try, even just spending an hour or two messing around, to experience a way of developing web apps that's likely a bit different to what you're used to, but feels familiar enough that it doesn't require a big mental leap.

nickreese 4 years ago

Having talked to a ton of friends about Svelte, Typescript support has always been the biggest push-back for adoption.

Stoked for Svelte to support it.

We've been using Svelte in production and I can't speak highly enough about the developer experience. Absolute game changer for our ssite that use it.

  • rawoke083600 4 years ago

    I LOVEE Svelte, if your any sort of dev... try it out. It's a super small API, you can learn in a few hours. I'm not a frontend dev by trade, but compared to Angular(prev fav) it's soo much simpler.

  • G4BB3R 4 years ago

    Do you use pure svelte or with sapper? how is it compared to react?

    • nickreese 4 years ago

      We wrote our own SSG for https://elderguide.com. We tried Sapper but our data flow and routing needs were to complex and not a fit.

      Svelte is a dream compared to React. That said, I've never felt like React was the right solution for the problem.

      I've extensively used Gatsby and for static sites, React is absolutely overkill. For apps it can be nice.

      In both cases my go-to these days is Svelte.

      • uxcolumbo 4 years ago

        Nice site and real snappy.

        I haven't used Svelte yet - but am interested.

        Can you explain a bit more about what you mean with your data flow and routing needs were too complex for Sapper.

        And what makes Svelte a dream compared to React?

        • nickreese 4 years ago

          Sapper's data flow uses a file based routing system similar to /blog/[id].svelte becomes /blog/:id/. If you are familiar with Next.js then you'll recognize this.

          Our primary problem with Sapper is that we wanted our URL structure to be such that you can't tightly route a template/view by just looking at their URL. /senior-living/blog-post/ and /senior-living/nursing-home-name/ need to live side-by-side.

          This forced us to build our own custom routing system, what we call an "inverted router" for our SSG.

          Also we found it less than elegant to use DB queries with Sapper and had a lot of concerns about what was actually on the client and what wasn't.

          As for why we swear by Svelte:

          * Bundle size. For SEO focused sites React is overkill.

          * Stores compared to Mobx or other state management

          * $: reactivity

          * No css-in-js hacks required. Css is automatically scoped, but can be easily globally scoped.

          * Single file components are just beautiful.

          * We've built in the ability to SSR our entire site, but only hydrate the parts that need to be. This is a game changer for page size and not pushing your data twice to the client.

          • nickreese 4 years ago

            We're working on open sourcing our entire SSG in the next 3-4 months.

            As it currently stands the SSG is super opinionated and we did several things quite unconventionally, so we are validating some of our ideas by building out another site besides elderguide.com to make sure these decisions indeed work across a lot of use cases.

            Once this second site is out the door we want to add TS support natively to the SSG and then we'll release it.

          • jfengel 4 years ago

            I just ran through the tutorial, and I really liked the $-for-reactivity part. That's clever and good.

            But then they introduced a whole new language for loops and control structures, and I really prefer JSX for that. JSX nails a sweet spot of bog-standard Javascript/Typescript, with enough HTML syntactic sugar to very natural web-pagey parts. As long as TS/JS is already in there, I'd rather use it everywhere.

            I don't know it well enough to know if that's a necessary feature, or if the language will evolve to something closer to my sensibilities. I will probably give it a try in the future, especially if I want something more performance focused. (The virtual DOM overhead is real and the separate state mechanism is far less elegant than Svelte's solution.)

          • Kabootit 4 years ago

            > Single file components are just beautiful.

            Not only in structure, but how they compose. The typical top-down tree components composition is typical. What is not immediately obvious is how child components can expose functionality upstream. So simple.

          • uxcolumbo 4 years ago

            Thanks for clarifying.

            Is your custom built routing system open source?

            I can imagine the Svelte community could benefit from it.

          • danr4 4 years ago

            Sounds very interesting. Any plans on open sourcing?

      • lurker42 4 years ago

        submitting your contact form without any filled in details throws a graphql mutation error :)

  • The_rationalist 4 years ago

    What would it bring in ergonomics and expressivity versus Vue ?

    • kjksf 4 years ago

      Those things really need to be experienced to be understood, so just try Svelte in a toy project. Or go through the interactive tutorial https://svelte.dev/tutorial/basics

      I used both React and Vue and am now only using Svelte.

      You type less. Significantly less.

      The thing you type is simpler. I tend to get lost in Vue's object structure.

      What you type is closer to HTML/CSS/JavaScript than what you type in React/Vue. It's therefore easier to understand what gets generated.

      The seamless reactivity is awesome.

      Scoped CSS support is built-in so you don't need css-in-js hacks.

      Built-in support for data (stores) is excellent.

      The final bundle is smaller and faster.

      There's more but the above are the major points.

      The only downside is smaller ecosystem. But I don't care because I'm in the camp of minimizing my dependencies.

      • preommr 4 years ago

        > Scoped CSS support is built-in so you don't need css-in-js hacks.

        vue/react also have scoped css, but built into the building process using loaders rather than being a feature of the frameworks.

        • buzzerbetrayed 4 years ago

          Less time setting up build processes is another win you git with Svelte, in my experience.

    • nickreese 4 years ago

      I haven't used Vue extensively since what was probably v1 so I'm likely the wrong person to comment on this.

      That said, I find that Svelte aligns more with my/our team's mental model about how the web should work and that is why went with it for our sites.

      Just like with Vue you can write your JS/CSS/HTML in a single file, but the reactivity and state management is much easier to reason about than what we've seen elsewhere.

      - `$:` is great.

      - Stores and derived stores are amazing.

      - Data binding / rerendering is really intuitive.

      That said, the biggest headache in building our own SSG was getting SSR/Hydration working well, but that was mainly fighting Webpack and got easier when we went with Rollup.

      edit: formatting.

orange8 4 years ago

> I get almost as much benefit from the rigorous null checking in TS as I do from the typing. I would use it for that alone. [1]

This.

I suspect there is a certain way those who rave about TS like yourself write and structure their code (all code, regardless of language) in a way that naturally lends itself to strict typing. The "rigorous null checking" comment struck me as odd, as someone who has written JS for almost 20 years, I've just never had to think about, or use null values. I probably just use the good parts of the language and avoid the bad [2]

[1] https://news.ycombinator.com/item?id=23913294

[2] https://www.oreilly.com/library/view/javascript-the-good/978...

  • spion 4 years ago

    You can't avoid null and undefined in your code unless you avoid almost every language feature. Two particularly common ones:

    * Accessing a missing property or method results with undefined. Hope you remember the exact method names and field names of all objects in your codebase!

    * Using "str".match(regex) results with null if there are no matches.

    • orange8 4 years ago

      > You can't avoid null and undefined

      We are speaking about just null, not "null and undefined". Believe it or not, I simply do not use null in JS. Study the concept of "truthy and falsy" in JS.

      > Accessing a missing property or method results with undefined. Hope you remember the exact method names and field names of all objects in your codebase!

      I don't. I do however structure my code predictably, using consistent naming conventions and patterns. I hope you do realize JS existed for over 20 years before TS, and complex apps like gmaps and google docx were built entirely in JS.

      > Using "str".match(regex) results with null if there are no matches.

      const match = /bar/.exec("str");

      if( match ){

        // am only interested in what happens if foo returns a *truthy* result.
       
        // The exact type of a falsy result is irrelevant, it either matches (truthy) or it doesn't (falsey)
      
      }
      • spion 4 years ago

        If you forget to do the check, you will get a falsy value. Hope you remember to do it every single time, and hope all your team members remember!

        If a team member writes

          function extractEmail(text) {
            return x.match(/someregex/);
          }
        
        and you call extractEmail(x), you might get a null value.

        If you assume you can't get a null value, you might try to do further processing:

          let [name, host] = extractEmail(x).split('@')
        
        and get a type error thrown. That is, if you're lucky.

        In the more common situation, you will actually save that to a database and that database will happen to accept null values by default, and then all hell will break loose in another totally distant bit of the code that naively fetches a list of emails from the table, grouped by host name. And you will have to chase down the bit of code that inserted that null in.

        This is approximately what development without types looks like. When this happens to you, I hope you remember the following bit of advice: It doesn't have to be this way :) Alternatively you can start doing paranoid validation everywhere. That works too, except the nice thing about a type system is that it can properly track whether you need to do that or not (see https://github.com/spion/branded-types for one TS technique on how to do that)

      • schwartzworld 4 years ago

        > We are speaking about just null, not "null and undefined". Believe it or not, I simply do not use null in JS. Study the concept of "truthy and falsy" in JS.

        I'm anti-TS, but there is a meaningful difference between null and undefined. Most of the time it's enough to check for falsy values, but there are times when you will want a distinction between a missing value and a value of null.

        https://i.stack.imgur.com/T9M2J.png

        • orange8 4 years ago

          Do you have a concrete example of such a time?

          • schwartzworld 4 years ago

            Undefined represents the absence of information altogether. In JavaScript any key can be called on any object and if it doesn't exist it will return undefined. If you put a typo in the key name, you get undefined. If you've never set it, you get undefined.

            Null, on the other hand, is not a lack of information. It's an absolute value just as much so as any number or string or array.

            They're both falsey values, but so is the number zero. An item with a price of zero dollars is not the same as an item with an undefined price, nor is it the same as an item that explicitly has no price, i.e. null. You may not choose to model your data that way, but the terms are still meaningful, and your UI might have to change to reflect the different falsey values.

            Most common case I could think of, would be in making a request from a server, using something like Apollo. `const [ data ] = useQuery(SomeQuery)` The data that comes from the server is undefined until you make the request, but null could be a valid response.

      • Vinnl 4 years ago

        > We are speaking about just null, not "null and undefined".

        Maybe you are, but when people are talking about using TS just for the strict null checking, they typically refer to the (default-on) `strictNullChecks` config option, that is about both null and undefined.

        • orange8 4 years ago

          My point is I never use null or worry about "strict null checking" or even what that is in the first place or even how it is configured.

          • Vinnl 4 years ago

            Well, good for you, bit you can run into the exact same problems with undefined (which you do use), and TypeScript still helps with those in the exact same way.

            Which is to say: whether you use null or undefined is not really relevant to the point that was being made...

            • orange8 4 years ago

              Thank you. I use undefined very rarely, usually with a hacky looking: "typeof foo === 'undefined'". I'd still rather just type that though than having to setup up TS. Don't get me wrong, TS is great for the eco-system, for examples it powers the intellisense behind vscode which I use daily. I just do not need to use it directly, so good for me indeed.

      • bobisme 4 years ago

        > complex apps like gmaps and Google docs were written entirely in JS

        I always assumed complex Google apps from that era were built with GWT, which would mean Java.

        • Zacru 4 years ago

          No, but they were written using the Closure Compiler type annotations. So closer to TS than plain JS.

          • orange8 4 years ago

            Closure compiler was released in 2009, google maps in 2005. So no, you've got it all wrong. The only thing limiting you from using the full power of JS is your mindset. And Google maps is just one example, others include nodejs, electron, react, vue, svelte....

      • mekster 4 years ago

        null and undefined are very different. Not sure how you leave null out of your code.

        You never interact with database? You're not supposed to pass undefined as NULL value.

        And a variable that is waiting to be defined is very different from a value that received null as a result.

        Dealing all those mixed up as falsy is a bad design.

        • orange8 4 years ago

          I've already mentioned this above, please look up falsy and truthy values in JS. Null, false, 0, undefined and "" can be treated pretty much the same in 99% of your JS code. JS is after-all still a dynamic language, and there is nothing stopping you from making use of its dynamic features.

nojvek 4 years ago

TS really shines when you have to work with other people’s code. This week I probably touched about 2000+ files and changes various apis. TS was really great in giving that confidence that what I am calling actually existed.

I had ~2000 errors and slowly worked to 0. tsc —watch is so good for iterative development.

And LSP (Language Server Protocol) really is a boon for the industry. So many tools can work together. Thank you VSCode for paving the way to an open protocol.

seanwilson 4 years ago

Are the HTML templates type checked as well?

I'm playing with Vue version 3 with TypeScript using JSX instead of the usual HTML templates and pretty happy that it's all type checked. I have a similar project without JSX and the vast majority of the bugs are related to the logic in the HTML templates not being type checked.

  • dlbucci 4 years ago

    This has been my experience with AngularJS 1 and TypeScript as well. Looks like there's at least some support for it (Quote the link: You get autocompletion hints and type-checking as you're writing components, even in expressions inside markup). Not sure if it does things like restrict `value` to `input` elements or anything, or if it's just the expressions in the template.

  • smt88 4 years ago

    Try using Vue in WebStorm with their Vue plugin enabled, or use TSX with any IDE. Your "HTML" will be type-checked.

    • raihansaputra 4 years ago

      Vue with TS, on VSCode and Vetur, with Vetur Template Interpolation enabled (VTI) also typechecks the template.

    • joshstrange 4 years ago

      Hmm, I'm going to have to take another look at this then because I get auto-complete of variable properties in my html (IDEA + Vue plugin) but I don't get warnings about a variable possibly being null or undefined. But that may be outside the realm of possibility to check easily.

      • smt88 4 years ago

        > But that may be outside the realm of possibility to check easily.

        It depends. If you type-check your runtime input (e.g. form fields) then it works well.

dboreham 4 years ago

Switching from JS to Typescript was like moving from machine code to C. Note: machine code (hex) not assembler.

  • DaiPlusPlus 4 years ago

    JavaScript is getting more “typed” anyway - what with Promises and other objects/interfaces in the DOM being conceptually statically typed - where JavaScript’s type-juggling simply can’t help you - so writing JavaScript today against modern browser/NodeJS APIs feels like writing VBScript against ActiveX instead of writing in VBA/VB6: you can do essentially the same things, but you have no idea if your program will actually work or not.

    It would not surprise me if the ECMAScript folks just throw in the towel and adopt TypeScript into ECMAScript as its official type-annotation feature - like how Python is doing - except without the duplication of effort.

swyx 4 years ago

this has been eagerly anticipated for so long and is probably the #1 stated reason why people haven't tried out Svelte yet. so glad this is out!

  • outime 4 years ago

    It definitely was my #1 reason and I'm happy to see this announcement. I'll check Svelte out soon as it already looked quite promising to me.

jedimastert 4 years ago

I am a (very) hobbyist web dev, almost always working with vanilla HTML+JS. I seeing a while lot of people here who are saying that Typescript is an absolute must.

As someone who has no clue, and with all do respect, why would TypeScript be worth moving from just hitting save to introducing a build system and dependencies?

  • TiredGuy 4 years ago

    As someone who has used all kinds of tooling and typescript too but still goes back to vanilla js when possible, I relish being able to just hit save and refresh. Build steps and hot-reloading are annoying and complex, and with large projects they can sometimes become slow and frustrating.

    Please don't feel pressured to make your code more defensive by switching to a typed language. There is often a tendency to make things more complex in the name of safety especially when there's typing involved, and it's not always the right answer. Clean, readable, maintainable code can exist in dynamically typed programming languages, and don't let anyone tell you differently.

    The right balance between over- and under- engineering is something that changes based on who you work with and for, what you're truly trying to accomplish, when you need it by, how quickly you can iterate, and your own personal feelings of safety and joy of programming.

  • xupybd 4 years ago

    Hobby projects are served very well by js. Commercial ones not so much. Big teams with a mix of Personalities mean you get lots of errors and problems organising code. Typescript makes that a little more manageable.

  • runarberg 4 years ago

    I have been using TypeScript in JS[1] mostly seamlessly. Types are annotated using doc comments above the thing your annotating.

    It is a bit hard to define complex types. E.g. I couldn’t for the life of me annotate the return value of the pipe function:

        function pipe(init, ...ops) {
          return ops.reduce((acc, op) => op(acc), init)
        }
    
    For these instances they suggest writing a declaration file[2]. However I have found the documentation isn’t really clear on this usecase (in fact I find the documentation of TypeScript somewhat lacking in general).

    But overall getting these typehints into my editor environment has been worth it. And I haven’t had to sacrifice the save → run workflow.

    1: https://www.typescriptlang.org/docs/handbook/type-checking-j...

    2: https://www.typescriptlang.org/docs/handbook/declaration-fil...

    EDIT: An example annotated JS file for typescript: https://github.com/runarberg/strawberry-router/blob/master/s...

    `npm run check` just runs typescript’s type checker, there is no compile step.

    • bgschiller 4 years ago

      > E.g. I couldn’t for the life of me annotate the return value of the pipe function

      Don't feel bad, no one can do that (yet! I think it should be possible with Variadic Tuple Types, coming in TS 4). There are a couple of attempts[1][2], but they all lack in some way. Redux does it with a boatload of overloads [3].

      1: https://dev.to/ascorbic/creating-a-typed-compose-function-in...

      2: https://stackoverflow.com/a/53066700/1586229

      3: https://github.com/reduxjs/redux/blob/686d29b5d4e2dcb6709c16...

    • xsmasher 4 years ago

      If I understand your pipe function correctly - it takes an init value and a series of functions that map a type T to the same type T - then this should do it.

        function pipe<T>(init: T, ...ops: ((x: T) => T)[]): T{
          let r:T = ops.reduce((acc:T, op) => op(acc), init);
          return r;
        }
      
      I had 5 years experience fixing type errors in C++; typescript seems like a dream in comparison.

      Edit: I just realized your operations probably DON'T return the same type that they are passed; they probably work in a chain like (t:T) => U, then (u:U) => V, etc. Nevermind!

      • runarberg 4 years ago

        Yup, the annotation should be something like:

            type Ops<T, R, N> = [
              (x: T) => N[0],
              ...<n>((x: N[n]) => N[n + 1]),
              (x: N.last) => R,
            ];
        
            function pipe<T>(init: T): T;
            function pipe<R, T, Ops>(init: T, ...ops: ...Ops<T, R>): R;
  • cageface 4 years ago

    I get almost as much benefit from the rigorous null checking in TS as I do from the typing. I would use it for that alone.

  • gameswithgo 4 years ago

    in your use case it probably isn’t worth it. if you get a bigger project where you are using webpack and npm already, maybe it would be.

aabbcc1241 4 years ago

In my previous experience of "Svelte with Typescript", it merely remove the typings, no type checking at all.

Try in below example, it print out '12' without type related error message.

<script lang="ts"> let a: number = '1'; let b: number = 2; </script>

<p> c = {a + b} </p>

  • cetra3 4 years ago

    I've just tried this using the starter project they provide in the blog post, and it does catch the error:

    The error returned is `Type '"1"' is not assignable to type 'number'.`

    • aabbcc1241 4 years ago

      Thanks for pointing out. It's getting better overtime! I missed the existence of "svelte-check". I expected to see errors on the webpage like we usually see from angular/react/stencil.

      On svelte, the typescript error doesn't show up until you manually run svelte-check.

JadoJodo 4 years ago

Slightly off-topic but I'm curious anyway: Has the tooling for JavaScript improved with TypeScript's adoption? As a back-end developer, I feel like each time I've tried to dig in and start a JavaScript project from scratch has ended with me weeping after spending four hours fighting the tooling. Is there a better way?

  • hath995 4 years ago

    I start all my server side projects in TypeScript lately. There is enough support that it is actually very easy to get started. ts-node, npm @types, and many packages natively supporting ts help.

    The browser is a crazy environment and adds difficulty, but I find my server code can very strictly typed. The nodejs type definitions are good and if you pick an ORM library with good typescript support then both the in memory data structures and database objects can be well typed.

    The build step with typescript is basically negated by ts-node for the server. Alternatively, by using tsc --watch and some clever indirection I've enabled hot reloading for most of my server code. So just to be clear, I have types helping me code using vs-code, I save and immediately see changes on the server.

    If you know the tools well and how to set things up then TS + node can provide a better developer environment than many languages.

  • tmpz22 4 years ago

    IMO the issue has to do with linting and editors i.e. "how do I make the yellow squigglies go away" or silent compiler warnings in the console due to several layers of default linting rules again applied by your editor, or your React CLI, or your operating systems package manager. These are very unsexy problems that nobody has been able to solve over the past 5 years because ultimately they are opinionated.

  • qudat 4 years ago

    It's about the same as any other service, the only difference is every web app needs js. Try jumping into a python web service and talk to me about weeping from terrible tooling.

  • symlinkk 4 years ago

    Just use create-react-app, it’s not hard.

    • crooked-v 4 years ago

      I'd personally recommend Next.js instead. It's even more painless, seamlessly handles a lot of other concerns (like routing), and can be used both as an SSR server and to generate purely static HTML bundles.

aryonoco 4 years ago

Rich Harris (the creator of Svelte) just released a short 5 hour video course on Svelte on Frontend Masters as well. It's great intro and touches most common usecases and briefly introduces Sapper as well. If you already have a FEM subscription, this is a great time to get into Svelte.

zamalek 4 years ago

I've been using Svelte TS for a pet project for maybe 2 weeks now. It's fantastic. The VSCode plugin is also doing a great job.

I tried, and failed, to use Babel as the TS compiler - but TSC then Babel works just fine.

untog 4 years ago

Very happy about this. I tried to combine the two a few months ago and it was not a fun experience. Great to know I can give it another go now.

nojvek 4 years ago

Svelte is nice, but man I just want to use JSX. Don’t make me learn another templating language.

  • wirahx 4 years ago

    Svelte will never have JSX, not natively anyway. It's completely against the philosophy.

    Not all of us think JSX is a great thing. The "templating" language in Svelte isn't really a templating language at all, it's just Javascript with some (unavoidable) helpers. It takes about 2 minutes to learn since there are really only maybe 5 helpers.

  • ric2b 4 years ago

    Svelte templates aren't really a new language, it's just HTML where you can sprinkle in some curly braces to insert variables or js code.

  • aabbcc1241 4 years ago

    You can dev Svelte in TSX with svelte-draft

leejoramo 4 years ago

Unlike many who have not used Svelte due to lack of Typescript support, this may give my team reason to consider Typescript.

kylemh 4 years ago

Now I'm just waiting for some company to actually make an app with Sapper and Svelte and I'll give this a go.

  • wirahx 4 years ago

    https://beyonk.com

    Everything we do is written in Svelte + Sapper, not just our site, but all the backend apps as well that we use for admin + providers.

fb03 4 years ago

I was literally searching for this like, a week ago. Glad to finally see it land in a stable, first-class manner.

heapslip 4 years ago

Just so you know svelte + typescript + eslint is currently not working.

drol3 4 years ago

Great news!

Was my only blocker :)

nXqd 4 years ago

Yes, finally.

The_rationalist 4 years ago

How is Webstorm support with Svelte ?

  • mrath 4 years ago

    I believe there is no official plugin for Svelte. So it may not be as good as the support for React/Angular/Vue. But once Svelte is a bit more popular, I think JetBrains will release a plugin.

  • BMorearty 4 years ago

    Not bad. I’ve been using the Svelte plugin by Tomasz Błachut. But I don’t think the plugin supports TypeScript yet.

  • wirahx 4 years ago

    Easier, due to the language-server Svelte uses to support TypeScript. It should be relatively trivial for somebody to implement now.

  • lurker42 4 years ago

    you can use the LSP and get most things working.