23 ms·
Convert React JavaScript Code to TypeScript with Proper Typing
- ComputerGuru 9y agoWhy is lyft in the title?
- forgot-my-pw 9y agoIt's their repo.
- ggregoire 9y agoSame for Flow: https://github.com/billyvg/codemod-proptypes-to-flow https://github.com/billyvg/codemod-proptypes-to-flow
- ralmidani 9y agoHas anyone considered building with TS--from the ground up--a React-like library? It seems like TS could help deal with lots of data and validation errors in a more concise and predictable way.
- ggregoire 9y agoReact is built with Flow. Since Flow and TS achieve the same thing, I'm not sure a React-like library based on TS would bring anything new.
- ralmidani 9y agoI have looked at Flow. I have to admit, I am biased toward good-looking code. Unless you use something like LightScript[0], Flow's syntax is not as clean or straightforward as that of TS. Edit: I just took another look. I thought parameters had to be annotated via block comments (that's how you have to do it if using CoffeeScript 2). I was wrong. [0] http://www.lightscript.org/ http://www.lightscript.org/
- ggregoire 9y agoThe following example written in TS works in Flow too: type MyComponentProps = { prop1: string; prop2?: number; } type MyComponentState = { foo: number; bar: string; baz: number; } class MyComponent extends Component<MyComponentProps, MyComponentState> { Same syntax. Also, not sure how this could be more straightforward.
- ralmidani 9y agoThank you. I edited my comment after looking at the Flow website. My incorrect understanding came from seeing the atrocious "block comment Flow annotations" in CoffeeScript 2 (an otherwise adorable language) and thinking that was how you had to specify parameter types with Flow.
- brlewis 9y agoWhy would the type system need to be tightly coupled with the view library? Mithril works well with TS without having been designed specifically for it.
- boubiyeah 9y agoIt doesn't HAVE to, but usually libraries designed with a JS mindset don't lend themselves to type safety very well (JS coders like their magic strings and very dynamic types). Somehow React still managed pretty decently in that area whereas vueJS is a catastrophe.
- brlewis 9y agoI'd be interested to know how many DefinitelyTyped contributors agree with the "usually" part. My impression is that problems specifying types for existing libraries are the exception rather than the rule.
- boubiyeah 9y agoIt's true it's easier now that typescript has richer types (nullable, mapped, etc)
- aphexairlines 9y agoWell, there are over 10,000 occurrences of 'any' (which effectively gives up on type checking) in the DefinitelyTyped repository: https://github.com/DefinitelyTyped/DefinitelyTyped/search?q=any https://github.com/DefinitelyTyped/DefinitelyTyped/search?q=...
- shados 9y agoMany non-trivial libs are typed improperly, even when they can be done right. There's massive abuse of "any" type the moment anything gets semi-challenging. Also, a non-trivial amount of type definitions don't work in strict mode, which make things worse. Anything involving complicated higher order functions (like lodash/ramda's curry), or having a single method that can be used in various ways that don't fit well with TS' overloading mechanisms are often done wrong or poorly. Flow is a bit better at this, but the techniques it provides are not always well known, so the type definitions aren't that much better.
- seepel 9y agoMobx is built with typescript. https://github.com/mobxjs/mobx https://github.com/mobxjs/mobx
- deleted 9y ago[deleted]
- quicksnap 9y agoThe React bindings for TS are quite good--I used them every day, and they're solid. As for a ground-up approach, the bindings for ReasonML-react show how much effort it takes to have strong functional typing for React: https://github.com/reasonml/reason-react https://github.com/reasonml/reason-react I believe that there will be an effort to rewrite React in ReasonML in the future by core members. The goal is the leverage the power of Reason to obviate some of the weird parts of the current React internals. /shrug
- bcherny 9y agoReact is already typesafe. For Redux I wrote Babydux [0], which is a simplified Redux with the goal of being 100% typesafe. It's the only Redux I've seen with that level of safety. [0] https://github.com/bcherny/babydux https://github.com/bcherny/babydux
- o_____________o 9y agoNot "duckling"?
- styfle 9y ago"Redux for babies" sounds like an insult. It reminds me of this Nathan For You episode: https://www.youtube.com/watch?v=BNuuiydKlI0 https://www.youtube.com/watch?v=BNuuiydKlI0
- connorelsea 9y agoLooks like a nice library, but I'm not sold on the name
- vmware513 9y agoGlimmer.js faster and more elegant than react. https://github.com/glimmerjs https://github.com/glimmerjs
- christophilus 9y agoThis is a side-topic, but I recently attended a Yehuda Katz talk about glimmer. It sounds great. I'm personally really fond of ClojureScript. Glimmer seems to be very much tied to its own tooling and ecosystem. Do you think it would be possible to target glimmer from a functional programming language like ClojureScript or Reason without jumping through a ton of hoops?
- ralmidani 9y agoI used Ember for almost 2 years. My experience was mostly good (see my comment regarding Ember Data--which apparently has no counterpart for React), but it enforces breaking things up into separate files a little too stringently. Routes, Controllers (at least until Components can safely replace them), Components, Templates, and Helpers (even for the most trivial operations which, IMO, are OK to sometimes include in the view). Not to mention Ember does not use standard ES6 classes yet. You can scrap most of Ember and just use Glimmer Components, but then all you have is a View layer, so you are not much better off than you are using React. And you __still__ have to use separate template files and helper functions.
- DanRosenwasser 9y agoNerv is a React alternative that's been built with TypeScript. Check it out: https://github.com/NervJS/nerv https://github.com/NervJS/nerv
- solidr53 9y agoThis is what you need: https://dominicstpierre.com/using-typescript-to-publish-a-testable-react-npm-package-f3811b3c64e3 https://dominicstpierre.com/using-typescript-to-publish-a-te...
- ditonal 9y agoCode quality looks pretty low. Not surprising between the fact that Lyft is a mobile property without much JS, and Lyft having a reputation for having a bit of lower quality engineers.
- RubenSandwich 9y agoWhoa got any data to back up that claim? Cause otherwise it seems like an ad hominem attack.
- mohsen1 9y agoI have FactoryFactory in there. You can't call that low quality ;) :D I agree though, I'll write it differently today
- evanm 9y agosounds like someone failed a lyft interview
- ditonal 9y agoYou're right, my comment is filled with bias, Evan Madow, Senior Software Engineer at Lyft. Please go astroturf your mediocre repos somewhere else.
- J5892 9y agoWow, this grudge runs deep. Did a Lyft engineer kill your dog?
- matchbok 9y agojesus, grow up.
- dang 9y agoThe GP was an uncivil swipe, but this is a bannable offense. We'll let you off this time, but not if you do it again. Instead, please read https://news.ycombinator.com/newsguidelines.html https://news.ycombinator.com/newsguidelines.html and take the spirit of this site to heart: civil, substantive comments or please don't post.
- wdclubber 9y agoWhy?!!
- deleted 9y ago[deleted]
- seekbeak 9y agoPlease work. Please work. Please work. This couldn't come at a better time. I've got "convert site to TS" looming on my to-do list for a large web app. Anything that saves me some interface props/state typing tedium would be great.
- agopaul 9y agoI plan to move a small react project to TS so it will be easier to work with complex objects coming from API endpoints. Having used TS quite a bit with "vanilla" JS and seen the advantages of using strong typing (eg. easier refactoring), it's strange for me to see that the majority of React developers prefer to stick with ES6 instead of TS
- jwarren 9y agoYou might find one of the JSON to Typescript type converters handy, i.e. https://shakyshane.github.io/json-ts/ https://shakyshane.github.io/json-ts/
- mkern 9y agoThere's also https://transform.now.sh/ https://transform.now.sh/, which can handle a bunch of related transformations as well.
- ggregoire 9y agoMost JS developers have no or few experience with strongly typed languages. I think it's a thing you need to try by yourself to see the benefits. I was kind of an anti-TS some years ago ("it's too verbose, it's not JavaScript"), but since I used Flow for 1 year I now see the obvious benefits (my favorite being to have autocompletion for almost anything, and not having to wait the runtime to see that `user.fisrtname` is undefined). Also, probably some React developers would like to use TS/Flow and their manager says 'nope'.
- seanmcdirmid 9y agoI’m a heavy TS user, but the compilation step is a PITA compared to working with bare JavaScript. Sometimes I forget to build and I wonder why my program hasn’t changed. I wish browsers would suck in TS directly. It doesn’t require much translation to get the corresponding JS files, just ignoring some types and that’s it.
- jorblumesea 9y agoI just flipped over my React app to typescript + react, and as a word of warning, support for some React libs is sketchy. For example, typings for redux Thunks are wonky/problematic and required a few hacks to fix. Very cool stuff just buyer beware :) You will probably have to work around more than a few issues if you use anything more than vanilla React.
- styfle 9y agoNothing that a little `var unsafe = original as any;` couldn't solve!
- cloverich 9y agoTo be a bit more explanatory: You can cast to the "any" type by adding `as any` to any variable, and it will then work just like Javascript. Typescript will know not to infer types from it or complain about it, and for that variable (which could be a simple variable or an entire library) will work just as it would in regular javascript. I typically use this when testing out a new library that doesn't have Typescript types so I can get a feel for it (and if I like it, I"ll progressively add types to it; its a very nice process imo).
- mohsen1 9y agoAuthor here, ask me any questions you might have. We used this internally to convert a few repos. It's not perfect but gives you a head start for converting to TS. I also wrote about our experience with TypeScript at Lyft if you're interested: https://eng.lyft.com/typescript-at-lyft-64f0702346ea https://eng.lyft.com/typescript-at-lyft-64f0702346ea
- Maarten88 9y agoThank you for making this! I've done this conversion by hand many times and I'll certainly try your program for the next untyped component that I want to import.
- scoot 9y agoNot specific to your project, but I suspect you’ll know the answer: If React code contains sufficient information to infer type, why is a separate type system needed? (Or why can’t the same inference by made at compile time, rather than scattering the code with type definitions and external type files?)
- msoad 9y agoBecause propTypes are leaking into runtime. ASFAIK Flow originally wanted to use propTypes but decided to use compile time only type annotations
- interlocutor 9y agoHave you seen this related project: https://github.com/fuselabs/jsxtyper https://github.com/fuselabs/jsxtyper
- asdojasdosadsa 9y agoWould you suggest this to someone who has (pretty much) never used TypeScript? Case is, I am going to rewrite a project and this would be quite an interesting addition!
- jalvarado91 9y agoThank you for this. I have a slightly tangential question, can you point to some resources on the approach you used for this codemod? I see you used what seem to be native TS transforms. I've used a badly patched up jscodeshift and tscodeshift but they leave much to be desired.
- deleted 9y ago[deleted]
- Waterluvian 9y agoI really want to commit to TypeScript for React/Redux apps but I'm gun shy. I don't want to commit to all the added effort TypeScript brings because I'm not sure if apps of my size warrant it. I'm afraid that I will end up with an over-engineered solution for my various apps of 10-100 components.
- seekbeak 9y agoIt's such a no brainer after you use it for a while, and the time savings after the fact far make up for the initial learning curve. Just do a small project to muck around with first. Maybe something small that nobody has thought of, like a to-do list?
- gedy 9y ago> and the time savings after the fact Could you elaborate how? I used to heavily use typed languages, but after moving to JS 5 years ago, I don't miss types.
- Waterluvian 9y agoThe one time I think, "oof I really would have liked types here" is when I begin digging deep through a stack of calls to understand what values I should expect and are valid. This hurt me in Python too until I began using type hinting, which in my opinion is the best of both worlds: documenting types but not forcefully enforcing typing.
- ggregoire 9y ago- Get autocompletion for everything: object properties (eg. user.[firstname, lastname, etc]), type-specific methods (eg. thisIsAStringButYourEditorCantKnow.[list of string methods provided by your editor since you told him it's a string]), etc - Detect bugs and errors early, removes some kind of bugs (eg. typo errors: user.fisrtname, your editor will tell you fisrtname is not a property of user) - Help to refactor (eg. 'Rename Symbol' in VSC can't work on everything if your code isn't typed, eg. (X => X.someProperty), someProperty isn't renamable automatically since your editor doesn't know what's X) - Reduce extra error handling (eg. if (a === undefined || b === undefined || a is not a number || b is not a number) throw new Error(...)) - Reduce extra unit tests (eg. expect(add(5, undefined)).toThrowAnError(); expect(add(5, 'foo')).toThrowAnError();) - etc...
- soulnothing 9y agoI recently started a new project. I started with kotlin and react. I was working on creating typings for redux, router, etc. Encountered a lot of issues. Moved to typescript, things were great till I went to add redux and router. There were typing issues being worked out in the recent development branch. A few weeks back. I love typescript. The IDE experience via visual studio is great. But I was burning a lot of time working on type libraries/definitions. I switched to flow. I miss visual studio code and some of the typescript features. But adding typing to a react project, especially with redux and immutable is great. The typing ecosystem of flow and typescript is truly impressive. With support for union types, strong structures. Really good inference. I'm just waiting for better pattern matching with active expressions. Please steal that from F#. This is also interesting for kotlin. https://github.com/Kotlin/ts2kt https://github.com/Kotlin/ts2kt
- StreamBright 9y agoHave you seen Reason yet? It has pattern matching. https://reasonml.github.io/docs/en/pattern-matching.html https://reasonml.github.io/docs/en/pattern-matching.html
- soulnothing 9y agoI haven't yet thank you. I like the ocaml influence.
- bratsche 9y agoSince you mentioned F# above, have you seen Fable? http://fable.io/ http://fable.io/
- thangngoc89 9y agoReasonML is OCaml. The syntax is different but the semantic is the same, it uses the same OCaml compiler
- boubiyeah 9y agoThat's pretty much the only thing I like from reason. it's still very goofy. <strong> (ReasonReact.stringToElement(string_of_int(count))) </strong> Compared to <strong>{ count }</strong> in ReactTS... The interop with JS is pretty verbose too. The tooling... Doesn't work at all? :p It might get there eventually but it doesn't seem like facebook has more than 1 or 2 engineers working on it.
- benjaminjackman 9y agoSo proptypes can be inspected at runtime. Does anyone have any success with tools that can turn Typescript types into runtime walkable datastructures or do code- generation / execute macros based on them as part of the build process? I use typescript quite a bit and am starting to hit some patterns that could be abstracted nicely if metaprogramming tools were in the shed.
- dvdsgl 9y agoquicktype (https://app.quicktype.io/ https://app.quicktype.io/) can generate TypeScript types from JSON, Schema, and GraphQL, and it also emits a runtime type representation to do dynamic typechecking. Perhaps this isn't exactly what you're looking for but you could easily modify it to generate whatever code you'd like. We have an experimental Handlebar-based templating feature to make customizing the generated code easier.
- joe-stanton 9y agoYou might be interested in this: https://github.com/gcanti/io-ts https://github.com/gcanti/io-ts and many related projects by Giulio.
- joe-stanton 9y agoBeforehand I built something very similar to what you described for Flow (https://hackernoon.com/runtime-introspection-of-flow-types-ddb7e5b042a5 https://hackernoon.com/runtime-introspection-of-flow-types-d...). Many others superseded this implementation, the above being one example.
- tehno 9y agoThere's also very similar project at https://github.com/pelotom/runtypes https://github.com/pelotom/runtypes that our company uses. Don't have enough experience with it yet to say which is better, io-ts on runtypes.
- TheCoreh 9y agoLooks really nice! I have an existing codebase that I might try this on. One feedback: Wouldn't interface MyComponentState { foo: number; bar: string; baz: number; } Be a little more idiomatic than type MyComponentState = { foo: number; bar: string; baz: number; } ?
- towndrunk 9y agoTake a look at some of the code samples in this post where the author is trying to make Redux work better with types in TypeScript. In my opinion, you get to the point where the code looks a mess and looks difficult to maintain. There is no way a beginner is going to figure this all out. https://medium.com/@danschuman/redux-guards-for-typescript-1b2dc2ed4790 https://medium.com/@danschuman/redux-guards-for-typescript-1...
- spion 9y agoThat article describes all the steps he took to get there, and he simply didin't make it clear what of that was included in the end result (its just a generic action creator and type guard)