inferring arguments types based on others

Is it possible to infer the type of a subset of arguments, based on some other arguments in typescript? See an example below

type FormValues = {
  name: string;
  height: number;
  birthDate: Date;
}


const [value, setValue] = useState<Partial<FormValues>>({});

const setFieldValue = (field: keyof FormValues, value: FormValues[field]) => {
  setValue(prev => ({ ...prev, field: value }));
}

I know why wouldn’t it work. But couldn’t verify that it’s either not possible in typescript or there is an alternative.

Answer

Try to add extra generic.

type FormValues = {
  name: string;
  height: number;
  birthDate: Date;
}


const [value, setValue] = useState<Partial<FormValues>>({});

const setFieldValue = <Field extends keyof FormValues>(field: Field, value: FormValues[Field]) => {
  setValue(prev => ({ ...prev, field: value }));
}

Here, in my article, you can find more techniques of arguments infering