Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Combat Pretzel
Jun 23, 2004

No, seriously... what kurds?!
Apparently Meta has their own Javascript engine for React Native called Hermes, and their team has been working on an AOT compiler leveraging types via TypeScript for xxxtreme performance. It's kind of what I want in a web browser (JIT using type info to improve performance).

Adbot
ADBOT LOVES YOU

Doom Mathematic
Sep 2, 2008

Combat Pretzel posted:

leveraging types via TypeScript for xxxtreme performance

About time. When I first heard about TypeScript I assumed that that kind of performance uplift was the entire point of the exercise.

smackfu
Jun 7, 2004

TIL that Typescript doesn’t follow semver, because basically every release has changes that someone would consider breaking. And 5.0 was just a major release, no more or less breaking than any other.

So what’s the best way to specify it as a dependency? Just say “>4.7” or whatever minimum sounds good?

Bruegels Fuckbooks
Sep 14, 2004

Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.

smackfu posted:

TIL that Typescript doesn’t follow semver, because basically every release has changes that someone would consider breaking. And 5.0 was just a major release, no more or less breaking than any other.

So what’s the best way to specify it as a dependency? Just say “>4.7” or whatever minimum sounds good?

unfortunately because ts doesn't support semver, you can't actually know whether or not a TS version will work unless you actually verify that your build works and unit tests pass with any given version of typescript. so if you're releasing a library written in typescript intended for public consumption, specifying, say, >4.7 may result in the new typescript version causing people's projects to break if they include your library.

I would suggest specifying both a minimum and maximum typescript version, and only updating the maximum version when you've actually run the build with newest typescript version to verify that it actually works - e.g. process would look something like this:
https://github.com/mswjs/msw/issues/1376#issuecomment-1229267340. A lot of libraries don't do this and just go with >4.7, and it does work, but past a certain size project, especially if you're using newer ts features, you're almost guaranteed SOMETHING non-obvious will break in the new typescript version, and it's much easier to figure out what went on that way rather than the completely random errors you will see from the people using bleeding edge typescript versions.

El Gar
Apr 12, 2007

Hey Trophy...

Please also note how the example given there is declaring typescript as a peerDependency. This is more important than folks may realize, because it tells npm et al that typescript needs to live alongside your package in that version, not just as a subdependency. One reason for this is because in a typical typescript app, if you have multiple versions of typescript in your tree you get some unexpected breakages. Peer dependencies are an attempt to mitigate this because npm will warn if there is an incompatibility between peerDependencies, whereas with normal ones it will just put whatever version works into your packages subdependencies. They don't totally solve the problem, and the end-user needs to do their own due diligence to make sure only one copy of typescript is in their tree, but setting it as a peerDependency makes that job easier and is more helpful to the community in general.

This is also why it's best to still use ranges, even if you're setting an upper bound. If you pin to a specific typescript version it is virtually impossible to deduplicate typescript unless every single dependency in your tree has that exact version in range. If even one other pins to a different version you're either out of luck or have to start implementing overrides.

fuf
Sep 12, 2004

haha
I feel like I'm missing something with state management in React, specifically with large arrays.

My app has a large (well, like 800 or so) array of "card" elements, with various properties that get toggled on a per-card basis.

The various state solutions I've tried (React's useState, zustand, and most recently preact signals) all treat state arrays as immutable, so if I want to change the "enabled" property of a single card, then instead of:

code:
card.enabled = false
I have to do something like:
code:
updateCard({
...card,
enabled: false
})

// updateCard.js
updateCard = (card) => {
  state.cards = state.cards.map((c) => {
    if (c.id === card.id) {
      return card;
    }
    return c;
  });
};
(there might be a better way of doing this, but the principle of having to replace the entire array with a new array after each update is the same).

Because of this approach, my app feels really sluggish. Even if most of the cards aren't rendered, there's still a noticeable delay when changing any property of a card because it has to update the entire array.

I know packages like immer can help with updating immutable arrays, but I'm assuming the performance issue will be the same.

I was super excited when I discovered https://github.com/luisherranz/deepsignal because it achieves the dream of making state arrays mutable. So I can just do:

code:
card.enabled = false
and it magically works. It's also incredibly performant.

The issue I faced with this approach is that I can no longer listen for changes to the array. With the standard immutable array approach I can do something like:
code:
  useEffect(() => {
    syncToDb()
  }, [state.cards]);
and this works because replacing the entire state.cards array triggers the useEffect.

But this doesn't work with deepsignal because it's not replacing the entire array. I ended up doing some really clunky stuff with periodically checking for changes to decide when to write to the database, rather than the preferred option of just writing when there are changes.

Is there a state management solution that lets you treat arrays as mutable but also lets you trigger an effect when any property of any member of the array changes? Or is that just trying to have my cake and eat it?

I don't mind immutable arrays if I could figure out a way to improve performance...

Osmosisch
Sep 9, 2007

I shall make everyone look like me! Then when they trick each other, they will say "oh that Coyote, he is the smartest one, he can even trick the great Coyote."



Grimey Drawer
Looping over 800 values is never enough to be something to cause the browser to be sluggish - you probably have some other expensive re-rendering in there.

Either way, if you just keep the cards in an object keyed by id instead of an array, and replace them by going


JavaScript code:

setcards({...cards, [updatedCard.id]: updatedCard})

You can be sure that the issue isn't the updating.

fuf
Sep 12, 2004

haha

Osmosisch posted:

keep the cards in an object keyed by id instead of an array

Oh interesting I've never seen that before. I have a lot of places where I'm doing cards.filter and cards.map etc. though, how would I do all that normal array stuff if cards is an object?

Roadie
Jun 30, 2013

fuf posted:

Oh interesting I've never seen that before. I have a lot of places where I'm doing cards.filter and cards.map etc. though, how would I do all that normal array stuff if cards is an object?

You're looking for Object.entries().

Ima Computer
Oct 28, 2007

Stop all the downloading!

Help computer.
I agree with Osmosisch that the performance issues are probably caused more by rendering 800 expensive components (which you can solve with virtualization/windowing and/or memoization) than by how you're managing immutable updates to the array.

Using an object as a map is a significantly worse solution here though, especially if maintaining the order of items in the list is important. It also means you have to call Object.entries() on every render before you can iterate over the items, which is going to have higher rendering computation cost and memory usage in comparison to just using an array in the first place.

This is a problem space that's solved pretty nicely by atomic state management libraries like Recoil and Jotai. The splitAtom utility from Jotai especially seems like it would be a good fit here.

fuf
Sep 12, 2004

haha
Yeah you guys are right that the performance issue is because of re-renders rather than replacing the array as such. But it's related because if I'm rendering my array of cards and I update one card and it replaces the whole array (because it is immutable) then it has to re-render the whole list, which is slow. But with deepsignal I could update one card and it would magically only re-render that one card in the list and it was really fast. It was honestly the dream solution apart from this issue of not being able to run a useEffect to save to db when the array changes.

Ima Computer posted:

Using an object as a map is a significantly worse solution here though, especially if maintaining the order of items in the list is important. It also means you have to call Object.entries() on every render before you can iterate over the items, which is going to have higher rendering computation cost and memory usage in comparison to just using an array in the first place.

I'm glad I'm not the only one who thought this was a weird suggestion. I've never seen any mention of using objects instead of arrays for state in React.

Ima Computer posted:

This is a problem space that's solved pretty nicely by atomic state management libraries like Recoil and Jotai. The splitAtom utility from Jotai especially seems like it would be a good fit here.

Oh yeah that Jotai splitAtom thing does look very promising, thank you. I might give it a whirl.

Osmosisch
Sep 9, 2007

I shall make everyone look like me! Then when they trick each other, they will say "oh that Coyote, he is the smartest one, he can even trick the great Coyote."



Grimey Drawer
Oh no, it wasn't meant as a final solution, more as a way of checking whether the updating was the issue. Sorry if that wasn't clear. I was only addressing that part of your post. The point being to update something without creating a new object/reference.

The real issue is of course like you said having a giant data blob as the root of state that causes everything to re-render if you're not careful. One main way to avoid unneccessary re-renders for child components is using useMemo where possible. Looks like splitAtom is also a really nice solution though, hiding the complexity.

fuf
Sep 12, 2004

haha

Osmosisch posted:

Oh no, it wasn't meant as a final solution, more as a way of checking whether the updating was the issue. Sorry if that wasn't clear.

Oh I see, no worries, thanks for the replies!

Ima Computer
Oct 28, 2007

Stop all the downloading!

Help computer.
I'm not sure if using an object as a map would actually help troubleshoot the issue.

Cloning an object and overwriting a property isn't really that much different from cloning an array and swapping one of its elements. It still gives you a new reference and it still requires a loop - its just a loop that's hidden behind syntax sugar (the object spread) and which iterates over a list of string keys instead of array indices.

smackfu
Jun 7, 2004

I’m a little suspicious that something else is triggering the rerender, that you aren’t even noticing. That’s kind of the curse of React.

abraham linksys
Sep 6, 2010

:darksouls:
There's like five threads I could ask this in, but I figure this one's at least more appropriate than the frontend thread: what's the deal with TypeScript and HTTP frameworks these days?

We have a "BFF" service at work, written in TypeScript. This service just has a bunch of endpoints that make calls to our backend services and return formatted data for the clients to use. The backend services are Java/Kotlin/Python and we use a mixture of gRPC and HTTP calls to them (mostly HTTP right now, eventually more gRPC). The clients are a couple web apps and a mobile app.

This service was initially written using plain ol' Express by a bunch of mobile devs who did not actually understand how TypeScript worked*. This lead to a few issues:

1. The request values for a lot of endpoints are not typed or validated. There's a lot of req.query, req.body, and req.params access that is completely untyped. Even when these are typed, they're usually not actually runtime-validated, since apparently no one who worked on this service before me understood that TypeScript types do not exist at runtime.

2. Only some of the response values for endpoints are typed, because you can just res.send(whatever the hell you want) in Express. Some of our endpoints have Swagger-via-JSDoc annotations, but these are usually horrendously inaccurate or at minimum out-of-date and missing things.

3. None of our HTTP calls to backend services have any kind of runtime validation that the responses for those calls match what the BFF (and downstream consumers) theoretically are expecting.

A couple years ago, another developer added tsoa to try to solve (1) and (2). We've incrementally adopted this and it mostly works. It's annoying to have an extra compile step, and a dependency on legacy decorators, but we've set it up so that it auto rebuilds in dev and works as expected.

This year, I decided I finally wanted to take a crack at (3). We'd solved this in one of our frontends that use TypeScript using zod for validation. This immediately exploded because tsoa can't generate using zod's infer type, meaning that any time one of BFF's endpoints directly return an object from a backend service (which is often!), we'd have to manually define both the zod schema and a TypeScript type that tsoa can handle. I really don't want to do this! I think it's also a tough sell to my coworkers! Honestly it's not that much boilerplate but it's enough I know I'm gonna get pushback.

So I'm wondering... what else is out there? Should we be using, for example, NestJS to have typed endpoints without this weird compile step? I know you can use NestJS's Swagger system with zod using zod-nestjs, so it's at the top of my list, but I'm sure there's other options.

Anything we can adopt incrementally in an existing Express app is best - we have enough endpoints that doing one wide switch is going to be hard. For now, I've actually still been converting our legacy endpoints to tsoa just so that we have a common base, but also trying to split up some of the endpoints that have a bunch of logic in the route handler so that they have separate business logic modules, and making sure nothing is using the req/res objects directly so that we shouldn't need to adapt that logic for a new HTTP framework.

* the issue here is not "mobile devs bad," it's that they assumed that TypeScript worked like Swift or Kotlin types, and trying to explain to them that "no, the as operator does not actually do anything at runtime" got a lot of surprised reactions

Harriet Carker
Jun 2, 2009

I started a new job recently. The most senior frontend guy is vehemently opposed to TypeScript for reasons I don't quite understand (understanding these reasons is obviously step 1). He put up a ton of resistance when I mentioned introducing it, claiming it's too full of quirks. I don't feel like rocking the boat too much since I'm new but curious if anyone had heard any particularly convincing reasons to not use TS in a modern React app. I've been using it for about 5 years and going back to plain JS feels awful so far.

abraham linksys
Sep 6, 2010

:darksouls:

Harriet Carker posted:

I started a new job recently. The most senior frontend guy is vehemently opposed to TypeScript for reasons I don't quite understand (understanding these reasons is obviously step 1). He put up a ton of resistance when I mentioned introducing it, claiming it's too full of quirks. I don't feel like rocking the boat too much since I'm new but curious if anyone had heard any particularly convincing reasons to not use TS in a modern React app. I've been using it for about 5 years and going back to plain JS feels awful so far.

i've heard "typescript is quirky" mean two different things:

1. typescript will limit your technology choices to things that integrate well with typescript. sometimes this means adding additional dependencies to your project that can be quirky in their own ways. a good example of this was how vue 2 relied on an extremely janky third-party vscode plugin to get any kind of useful typing, and it was a pretty miserable experience if you didn't get it set up just-right. another common example is how vanilla redux and a lot of libraries and patterns from early react/redux don't play well with typescript because they can't be easily typed (this is why our old react codebase at my employer isn't typed, we don't have bandwidth to make the massive switch to redux-toolkit or whatever). you also might have trouble setting up typescript in your build pipeline, jest configuration, etc etc

that said, in the context of a "modern React app," you should be able to adopt typescript relatively easily. the build pipeline stuff is a lot easier now, especially if you're using a framework like next or remix. might be worth asking if he has specific concerns around specific libraries or patterns that don't play nice with typescript

2. typescript requires understanding of type systems in general, which a lot of frontend engineers don't have! you can pick a lot up by cargo-culting, but i've seen feature branches get stuck because an engineer couldn't figure out how to type something well and was too embarrassed to commit something with an `any` type (or scared off by the linter yelling at them about it). it's also a really loving advanced type system, and i've seen engineers (such as myself) fall down rabbit holes of trying to type things "elegantly" without boilerplate, and before you know it you've got 20 open stack overflow tabs about conditional typing and you've written 20 lines of type annotations that don't actually do anything but let you save a bit of copy-pasting.

i've also heard typescript described as "quirky" by backend devs because of the lack of type soundness (after all, it is an erased types system), and i have definitely had that problem myself (see my giant post above yours about zod and tsoa and runtime validation :v:). i think that can really turn people off, because they get this idea in their head that if a type system isn't "perfect" then that makes it useless.

smackfu
Jun 7, 2004

He probably tried it once for a week two years ago, ran into some issues, and has his opinions set in stone now. Don’t be him.

fsif
Jul 18, 2003

I can't speak for your colleague's concerns in particular, but a lot of the work I do in my day-to-day are short-term web projects/experiences that don't need to be maintained by large teams of developers over many years. For these projects, I'm not certain that the extra time spent writing types and debugging type errors is always offset by the time saved by seeing errors in your IDE or better IntelliSense. I can't sell these clients on their project having even one fewer feature in exchange for a tidier codebase.

On top of that, a lot of the projects I work on, too, can on short-notice have a number of different developers with different experience levels hopping on. It's not only a barrier for intern and junior level developers; a number of the great creative tech folks I work with (think WebGL developers) outright refuse to use it because of how it messes with their workflows.

teen phone cutie
Jun 18, 2012

last year i rewrote something awful from scratch because i hate myself

Harriet Carker posted:

I started a new job recently. The most senior frontend guy is vehemently opposed to TypeScript for reasons I don't quite understand (understanding these reasons is obviously step 1). He put up a ton of resistance when I mentioned introducing it, claiming it's too full of quirks. I don't feel like rocking the boat too much since I'm new but curious if anyone had heard any particularly convincing reasons to not use TS in a modern React app. I've been using it for about 5 years and going back to plain JS feels awful so far.

im in the same boat as you right now, just started a new job and trying to convince higher-up people i know what i'm talking about. my advice would be to wait a few months, commit some good code to the codebase, establish yourself as an expert, then try having that conversation again

maybe just with a proof-of-concept PR that says "hey look how nice typescript could make this codebase"

Symbolic Butt
Mar 22, 2009

(_!_)
Buglord
IIRC Typescript was very problematic with React in the beginning, so I guess it just stained his opinion forever.

smackfu
Jun 7, 2004

Wasn’t there a thing with tslint vs eslint too? And now tslint is dead and eslint does typescript so it’s all good.

Not to mention the whole Flow typing thing.

Bruegels Fuckbooks
Sep 14, 2004

Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.

Harriet Carker posted:

I started a new job recently. The most senior frontend guy is vehemently opposed to TypeScript for reasons I don't quite understand (understanding these reasons is obviously step 1). He put up a ton of resistance when I mentioned introducing it, claiming it's too full of quirks. I don't feel like rocking the boat too much since I'm new but curious if anyone had heard any particularly convincing reasons to not use TS in a modern React app. I've been using it for about 5 years and going back to plain JS feels awful so far.

I am a big typescript fan but it's a chore to take an existing js codebase, gently caress with the build process to make it compile typescript, track down definitions for all the 3rd party libraries, and actually convert it to ts so it's beneficial. That poo poo doesn't happen on its own.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
When I go back to old codebases it isn't the coding practices that bother me, it's the fact I still didn't appreciate typescript as much as I should and so didn't use it. I met one guy professionally who was against it. His reason was that dynamic types is a feature and that you're supposed to validate the type of an argument everywhere it's passed for reasons beyond what I could understand.

fsif
Jul 18, 2003

Okay so as the resident TypeScript hater* (I enjoy using it, I just don't think it's right for every project), one thing I have noticed recently-ish is something of a shift in tone from several prominent TS evangelists.

Here's Theo lecturing developers that they're only feeling unproductive with TS because they're using it wrong. It should never block the build step! Except it should on main, the most important build step. Simply create your own CI/CD pipeline configuration that treats preview and production branches differently. And also, feel free to just kind of ignore all the red squigglies until the end, then I guess you have to go back and address them then? And don't put the type in separate files, just kind of start using `as` to make things simpler (but don't use `any`).
https://www.youtube.com/watch?v=Xl02L1jy53c

And then here's Scott Tolinski and Wes Bos saying they ship with type errors and it's NBD, they'll go back and fix them later?
https://www.tiktok.com/embed/7304021566386343210

Seems like we're kind of reaching a point where developers are talking about how in real world practice, they're finding ways to modify their workflows to start selectively ignoring TypeScript.

Harriet Carker
Jun 2, 2009

Thanks for all the great advice everyone. I'm feeling some hardcore imposter syndrome with this guy because he seems like he knows what he's talking about but I don't quite understand, and I'm a little worried about pushing back and being totally off-base.

We have a standard React app with a webpack bundler. I mentioned we could slowly introduce TS into new components without having to touch the old ones until we want to/have time, but he says introducing TS is all-or-nothing because:

quote:

In TS you have to import files like `import { blah } from './world.js` even though it's `world.ts` that's not allowed in TS+ESM. The filename is `world.ts` but because it's actually transpiled to JS and TS is just a lie on top, you have to import all the files as `.js`. You can'd do `./world` in Node.js ESM. It requires the file extension for node native module resolution in ES Modules.

Can anyone help me maybe understand what he means? I've never run into this issue and I'm super unclear, but I don't feel confident enough to engage in the discussion.

fsif
Jul 18, 2003

Harriet Carker posted:

Thanks for all the great advice everyone. I'm feeling some hardcore imposter syndrome with this guy because he seems like he knows what he's talking about but I don't quite understand, and I'm a little worried about pushing back and being totally off-base.

We have a standard React app with a webpack bundler. I mentioned we could slowly introduce TS into new components without having to touch the old ones until we want to/have time, but he says introducing TS is all-or-nothing because:

Can anyone help me maybe understand what he means? I've never run into this issue and I'm super unclear, but I don't feel confident enough to engage in the discussion.

My best professional advice is that if the person is more senior than you are and you're not feeling comfortable enough to refute their arguments without asking for help on the Internet, you're probably best off just following their lead.

Harriet Carker
Jun 2, 2009

fsif posted:

My best professional advice is that if the person is more senior than you are and you're not feeling comfortable enough to refute their arguments without asking for help on the Internet, you're probably best off just following their lead.

This is actually probably really good advice, which I will take. Thanks!

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
Sometimes I want to go back to a more innocent time where I did my duty as a good programmer who listened to more experienced developers. But you can only have been right secretly without telling anybody about it so many times before you wanna explode.

Follow the advice given but also make it clear that you are thinking something different anyway, just do it a friendly conversational way.

necrotic
Aug 2, 2005
I owe my brother big time for this!

Harriet Carker posted:

Can anyone help me maybe understand what he means? I've never run into this issue and I'm super unclear, but I don't feel confident enough to engage in the discussion.

https://github.com/microsoft/TypeScript/issues/42151

https://github.com/microsoft/TypeScript/issues/16577

Here are some rather large issues related to the ESM behavior.

TS5 added some features to make this a little better, but it relies on your bundler to appropriately handle things , and sounds like it only works for TS files importing other TS files which would make it “all or nothing”.

https://devblogs.microsoft.com/typescript/announcing-typescript-5-0/

abraham linksys
Sep 6, 2010

:darksouls:
tbh that's not even a quirk of typescript as much as native ESM having the most awkward rollout of all time across every single runtime and bundler

our one node typescript service is still using "module": "CommonJS", and thankfully our react+typescript project just uses NextJS which configures the bundler part for us

MrMoo
Sep 14, 2000

It’s a bit sad devs would rather drop a platform rather than address the defects with the tooling that blocks integration.

Normally in webdev land that ignites creation of a dozen new tools.

Ima Computer
Oct 28, 2007

Stop all the downloading!

Help computer.
It's 2024. The war is over. TypeScript won. Every library nowadays either provides first-class support for TypeScript or has mature community-developed type definitions.

If your projects haven't at least partially adopted TypeScript yet, that's a sign of neglect.

Harriet Carker posted:

Can anyone help me maybe understand what he means? I've never run into this issue and I'm super unclear, but I don't feel confident enough to engage in the discussion.

Sounds odd. If you're using webpack, you shouldn't need to worry about that ESM<->CJS interop nonsense anyway. :shrug: The bundler should be normalizing all the modules while it's stitching them together into bundles. Modern versions of typescript support all sorts of different module resolution options - one of them has to match the behavior of your bundler.

teen phone cutie
Jun 18, 2012

last year i rewrote something awful from scratch because i hate myself
yeah sounds like bullshit to me, but either put up a PR to put your money where your mouth is and prove it can be done or just lay off him for a while

Harriet Carker
Jun 2, 2009

teen phone cutie posted:

yeah sounds like bullshit to me, but either put up a PR to put your money where your mouth is and prove it can be done or just lay off him for a while

For sure. I’m going to sit back and soak it all in for a bit. There’s no rush.

prisoner of waffles
May 8, 2007

Ah! well a-day! what evil looks
Had I from old and young!
Instead of the cross, the fishmech
About my neck was hung.

Harriet Carker posted:

We have a standard React app with a webpack bundler. I mentioned we could slowly introduce TS into new components without having to touch the old ones until we want to/have time, but he says introducing TS is all-or-nothing because:

quote:

In TS you have to import files like `import { blah } from './world.js` even though it's `world.ts` that's not allowed in TS+ESM. The filename is `world.ts` but because it's actually transpiled to JS and TS is just a lie on top, you have to import all the files as `.js`. You can'd do `./world` in Node.js ESM. It requires the file extension for node native module resolution in ES Modules.

Can anyone help me maybe understand what he means? I've never run into this issue and I'm super unclear, but I don't feel confident enough to engage in the discussion.

Hmm. It sounds to me like he's either got a specific problem with a bundler's support for Typescript that can be worked around OR he's making a mountain out of a molehill.

When and if you have time to just play around, you might see if you can disprove his contention that "introducing TS is all-or-nothing"; just see if you can take an existing bundler build and add one Typescript file and just enough config that it gets built and uses/is used by existing JavaScript code.

VagueRant
May 24, 2012
Losing my mind trying to understand a bit of syntax. My actual goal is turning it from an arrow function to a regular function declaration.

Technically using Typescript and the aws-embedded-metrics library if that gives any extra context.

code:
const publish = metricScope(metrics => async (input: ExampleObjType): Promise<MetricsLogger> => 
  metrics.someChainedFuncsThatPublishAMetric(input.exampleKey)
);

// Called as
publish({ exampleKey: 'example value' });
But to simplify, I'm clearly missing some key thing in my reading on how this is creating the 'metrics' value, and how I can turn it into a regular function:
code:
metricScope(metrics => async (input) => metrics.someChainedFuncs())

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
I don't mean to be demeaning in any way I pasted your exact post into chatgpt to see what it would say and it pretty much nailed this nail as hard as a nail could possibly be nailed.

quote:

To convert the arrow function to a regular function declaration, you need to explicitly define the function and its parameters. In your case, you have a function that takes a metrics argument and returns another function that takes an input argument. Here's how you can rewrite it using a regular function declaration:

TypeScript code:
const publish = function(metrics) {
  return async function(input) {
    return metrics.someChainedFuncsThatPublishAMetric(input.exampleKey);
  };
};

// Called as
await publish(metrics)({ exampleKey: 'example value' });
In this example, the publish function takes a metrics parameter and returns an asynchronous function that takes an input parameter. The body of the function remains the same, with the call to metrics.someChainedFuncsThatPublishAMetric(input.exampleKey).

Keep in mind that using arrow functions in this context can often lead to more concise and readable code. Arrow functions have lexical scoping for this, which can be beneficial in certain situations. However, if you specifically need a regular function declaration, the example above should help you achieve that.

I guess what it's missing is that if all you're trying to do is this concise you could make it one function. But all you've really done there is reconfigured the way someChainedFuncsThatPublishAMetric is called and renamed it.

TypeScript code:
async function publish(metrics, input) {
  return metrics.someChainedFuncsThatPublishAMetric(input.exampleKey);
}

// Called as
await publish(metrics, { exampleKey: 'example value' });

Adbot
ADBOT LOVES YOU

Osmosisch
Sep 9, 2007

I shall make everyone look like me! Then when they trick each other, they will say "oh that Coyote, he is the smartest one, he can even trick the great Coyote."



Grimey Drawer
I think it's even clearer if you define the named outer function in the non-assignment way, like so:

TypeScript code:
 function publish (metrics) {
  return async function(input) {
    return metrics.someChainedFuncsThatPublishAMetric(input.exampleKey);
  };
};

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply