#Typing reduce params

30 messages · Page 1 of 1 (latest)

lunar whale
#

I have an array of objects I'm trying to reduce, the sig looks like


sortedList.reduce((acc, movement, index) => {};

The infered type of acc is the type of sortedList, but Is it fine to specify acc should be an array and different object structure i specify, and how do i do this in the reduces signature?

orchid swift
#

you can specify the type parameter of reduce

lunar whale
#

I've used type assertion on the initialValue of my reduce, is that the way you'd approach or do you mean type something else?

orchid swift
#

reduce<number>(...), just specifying the type parameter of reduce?

lunar whale
#

sortedList.reduce((acc, movement, index) => {}, [] as (ProductFrom | ProductTo)[]);

#

is what i have

#

works all fine but i wonder if i should be expliclity typing differently or typing something else

orchid swift
#

...the type parameter of reduce

#

that code doesn't work though, (ProductFrom, ProductTo) isn't valid

#

did you mean [ProductFrom, ProductTo]

lunar whale
#

oh my bad typo

#

I suppose i can tuple it too right?

#

Unsure if that matters

orchid swift
#

they mean completely different things

lunar whale
#

Ah i wasn't aware

orchid swift
#

it absolutely matters 💀

lunar whale
#

What's the difference?

orchid swift
#

i don't know what you actually want there though so i can't say if you want a tuple or a union

orchid swift
# lunar whale What's the difference?

uh, everything? you'd get a better answer from "what're the similarities" and that answer would be "they're typescript types" and nothing else, really

lunar whale
#

I want to say the return type is an array, where the types in the array can be ProductFrom or ProductTo

orchid swift
#

that would be a union then

#

anyways, this is more about code style consistency then

#

in your codebase, if you want a variable of type string[] let's say, would you do const arr: string[] = []; or const arr = [] as string[];

#

if the latter, then your current code would be following that pattern, but if the former you'd use the type parameter

lunar whale
#

The former, ok so that's basically what im getting at

#

they mean the same thing

#

That's really useful ty

#

Is there somewhere i can read up about TS tuples btw? all i can see from offical ts is a playground link about them

lunar whale
#

tyvm