首页 > 解决方案 > 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.

标签: reactjstypescript

解决方案


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


推荐阅读