reactjs - 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.
解决方案
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
推荐阅读
- javascript - 从实时数据库中检索 currentUser 数据
- spring - 将 spring boot 从 2.1.9 升级到 2.2.0 ,现在启动时出现异常
- svg - 如何根据每个弧度百分比在svg圆中绘制几条弧?
- javascript - 使用 Angular firestore 在 firebase 中返回子集合
- spring - 从数据库中查找日期从 - 到的所有记录
- visual-studio-2019 - Roslynator - 如何禁用 .Net 4.7.2 的 C# 8.0 提示
- python - 查询 pandas 的 copy() 方法
- apache - Htaccess 和波浪号 (~) 重定向
- angular - Angular:用于仅用于视图转换值的管道,但我想根据参数值覆盖该值
- c# - 转换后的字符串 ToCharArray 未返回所需的值