3

If I have a constant with input props and a function that returns the input ids and its default value, like this:

const Inputs = [{label: "myInput1", id: "myId1"}, {label: "myInput2" , id: "myId2" }]
    
const getInputValues = () => Inputs.reduce( (acc, item) => ({...acc, [item.id] : 123  }), {} )

How can I define the return type of getInputValues in TypeScript?

Code

2
  • I don't want to use any. There is no way to do it without any? Commented Sep 28, 2020 at 16:40
  • Did you tried making an interface as your question title displays ? Commented Sep 28, 2020 at 16:46

2 Answers 2

3

The only way I could think of is to use const assertion for your Inputs constant:

const Inputs = [
  {label: "myInput1", id: "myId1"},
  {label: "myInput2", id: "myId2"},
] as const;

type InputIds = typeof Inputs[number]['id'];

function getInputValues(): Record<InputIds, number> {
  return Inputs.reduce((acc, item) => {
    return {...acc, [item.id]: 123};
  }, {} as Partial<Record<InputIds, number>>) as Record<InputIds, number>;
}
Sign up to request clarification or add additional context in comments.

2 Comments

{[K in InputIds]: number} can be replaced with Record<InputIds, number>,
@TitianCernicova-Dragomir Thank you! Definitely more readable. I edited my answer.
1

The best you can hope for here is Record<string, number>.

const getInputValues = ():Record<string,number> => 
    Inputs.reduce( (acc, item) => ({...acc, [item.id] : 123  }), {})

For even better type-safety, you might choose Record<string, number | undefined> which will force you to type-check any values you access.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.