Define interface by an array of values

Viewed 93

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 Answers

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>;
}

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.

Related