[英]Typescript type an object key with data
I've got this code how to type dynamically data param of onHandlerData function?我有这个代码如何动态输入 onHandlerData 函数的数据参数?
export interface UserFormDto {
credentials: UserCredentialsDto | null;
details: UserDetailsDto | null;
address: UserAddressDto | null;
}
const [data, setData] = useState<UserFormDto>({
credentials: null,
details: null,
address: null,
});
const onHandlerData = (
type: keyof UserFormDto,
data: UserFormDto["credentials"]
) => {
setData((data) => {
return { ...data, [type]: data };
});
};
First, there's a problem with the implementation of onHandlerData
(not just its types), you're shadowing the data
parameter with the data
parameter in the setData
callback.首先,
onHandlerData
的实现有问题(不仅仅是它的类型),你在setData
回调中用data
参数遮蔽了data
参数。 You'll need a different name for that.你需要一个不同的名字。
Once you have that, you can use a generic type parameter to handle ensuring type
and data
work together, like this:一旦你有了它,你就可以使用泛型类型参数来确保
type
和data
一起工作,就像这样:
const onHandlerData = <KeyType extends keyof UserFormDto,>(
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
type: KeyType,
// ^^^^^^^
data: UserFormDto[KeyType]
// ^^^^^^^^^^^^^^^^^^^^
) => {
setData((current) => {
return { ...current, [type]: data };
});
};
(The ,
after the generic type parameter definition is so that it works with JSX. It tells the parser that that <...>
thing isn't an element definition.) (中
,
后的泛型类型参数的定义是,这样它与JSX,它告诉解析器是<...>
的事情不是一个元素定义。)
One way to achieve it I could think of is to use generic, like this:我能想到的实现它的一种方法是使用泛型,如下所示:
const onHandlerData = <T extends keyof UserFormDTo>(
type: T,
data: UserFormDto[T]
) => {
setData((data) => {
return { ...data, [type]: data };
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.