0

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.

omid.n
  • 491
  • 5
  • 22

2 Answers2

1

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

1

As seen in the answer to a similar question, you can do as follows:

type ValueOf<T> = T[keyof T];


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


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

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

and any type used by a property of FormValues will pass validation.

theberzi
  • 2,142
  • 3
  • 20
  • 34