#Maintain types after mapping array

1 messages · Page 1 of 1 (latest)

soft dew
#

Not a typescript wizard, so I'm struggling a bit with this issue or maybe this is just a bad approach.

I have an array of objects called inputArray with a key called foo. Value of foo can be multiple types. I'm trying to have a function consume inputArray and return an Array of all foo values while maintaining their types.

meager mapleBOT
#
inori._.#0

Preview:```ts
type Input<T> = Array<{
value: T | null
error: string
}>

function processInputs<T>(inputs: Input<T>) {
const nullInput = inputs.find(
input => input.value === null
)

if (nullInput) {
// Handle err
return false
}

return inputs.map(input => input.value) as T[]
...```

wicked ruin
#

how is foo/err related to value/error?

meager mapleBOT
#
Jakob#8686

Preview:```ts
function processInputs<
T extends ReadonlyArray<{foo: any; err: string}>

(inputs: T) {
const nullInput = inputs.find(
input => input.foo === null
)

if (nullInput) {
// Handle err
return false
}

return inputs.map(input => input.foo) as {
[Key in keyof T]: T[Key]["foo"]
}
...```

soft dew
# wicked ruin how is foo/err related to value/error?

Sorry I was just simplifying the problem, but I also wanted to give code in the playground similar to what I am actually working with.

type Input<T> = Array<{
  value: T | null;
  error: string;
}>;

In my example foo is value and err is error, but I thought the word value as a key for an example wouldn't be clear.

But you nailed it in the playground. Thank you :D I appreciate the help. Will have to look over this and try to learn a thing or two.