在 React useState 挂钩中使用 Pick 实用程序类型时遇到问题
Having issues using Pick utility type with React useState hook
我试图理解为什么我不能使用 Pick
实用程序类型从我的界面中选择一个 属性 并使用它来键入我的组件的状态。
界面如下:
export interface IBooking {
...
propertyId: string | null;
...
}
然后在我的组件中有以下内容:
const [propertyId, setPropertyId] = useState<Pick<IBooking, 'propertyId'>>('some-id');
这是我得到的错误:
TS2345: Argument of type 'string' is not assignable to parameter of type 'Pick | (() => Pick )'.
但是,如果我只是将 Pick<IBooking, 'propertyId'>
替换为 string | null
,当然可以。我不明白有什么区别。这不正是 Pick
类型应该做的吗?我对实用程序类型没有太多经验,但我在另一个地方使用 Pick
类型非常好。是因为 useState
hook 的一些细节吗?
我在这里错过了什么?
提前致谢。
假设 IBooking
上的 propertyId
是 string | null
类型,那么它将是以下类型:
{
propertyId: string | null;
}
Pick 的结果是一个仅包含所列属性的对象。
您可以像这样使用 lookup type:
IBooking["propertyId"]
我试图理解为什么我不能使用 Pick
实用程序类型从我的界面中选择一个 属性 并使用它来键入我的组件的状态。
界面如下:
export interface IBooking {
...
propertyId: string | null;
...
}
然后在我的组件中有以下内容:
const [propertyId, setPropertyId] = useState<Pick<IBooking, 'propertyId'>>('some-id');
这是我得到的错误:
TS2345: Argument of type 'string' is not assignable to parameter of type 'Pick | (() => Pick )'.
但是,如果我只是将 Pick<IBooking, 'propertyId'>
替换为 string | null
,当然可以。我不明白有什么区别。这不正是 Pick
类型应该做的吗?我对实用程序类型没有太多经验,但我在另一个地方使用 Pick
类型非常好。是因为 useState
hook 的一些细节吗?
我在这里错过了什么?
提前致谢。
假设 IBooking
上的 propertyId
是 string | null
类型,那么它将是以下类型:
{
propertyId: string | null;
}
Pick 的结果是一个仅包含所列属性的对象。
您可以像这样使用 lookup type:
IBooking["propertyId"]