在制作自己的useState钩子时,如何使用带有工厂的Typescript泛型作为属性?



我正在尝试使用泛型来DRY类似的自定义钩子。我有一些传入的工厂函数。但是我得到一个输入错误。我将代码简化为一个最小的示例:

import { useState } from 'react';
type AType = {
a: string;
};
type BType = {
b: string;
};
type AData = {
data: AType;
};
type BData = {
data: BType;
};
function useAOrB<T extends AData | BData>(factory: () => T['data']): T | undefined {
const [value, setValue] = useState<T | undefined>(undefined);
const newData = factory();
const newValue = { data: newData };
setValue(newValue);
return value;
}
const aFactory = (): AType => ({ a: 'a' });
const bFactory = (): BType => ({ b: 'b' });
export const useA = useAOrB<AData>(aFactory);
export const useB = useAOrB<BData>(bFactory);
这给了我一个类型错误:
TS2345: Argument of type '{ data: T["data"]; }' is not assignable to parameter of type 'SetStateAction<T>'.
Type '{ data: T["data"]; }' is not assignable to type '(prevState: T) => T.
Type '{ data: T["data"]; }' provides no match for the signature '(prevState: T): T'.

我不明白为什么这不能通过类型检查,所有的东西都应该匹配。我该如何解决这个问题?

直接输入新值T:

const newValue = { data: newData } as T;//<- as T

操场上联系

最新更新