我想使用 React 的memo
对于一个具有generic https://www.typescriptlang.org/docs/handbook/generics.html争论。不幸的是,泛型参数默认为泛型,并且所有花哨的泛型推导逻辑都丢失了(TypeScript v3.5.2)。在下面的例子中WithMemo
(using React.memo
) 失败并显示:
Property 'length' does not exist on type 'string | number'.
Property 'length' does not exist on type 'number'.
而WithoutMemo
正如预期的那样工作。
interface TProps<T extends string | number> {
arg: T;
output: (o: T) => string;
}
const Test = <T extends string | number>(props: TProps<T>) => {
const { arg, output } = props;
return <div>{output(arg)} </div>;
};
const myArg = 'a string';
const WithoutMemo = <Test arg={myArg} output={o => `${o}: ${o.length}`} />;
const MemoTest = React.memo(Test);
const WithMemo = <MemoTest arg={myArg} output={o => `${o}: ${o.length}`} />;
我看过这个问题 https://stackoverflow.com/questions/53433989/react-memo-with-typescript-in-react,但我认为这与我的问题无关。
可能的解决方案
我找到了一个可能的解决方案通用接口但似乎有点粗糙:
const myArgStr = 'a string';
const myArgNo: number = 2;
const WithoutMemo = (
<>
<Test arg={myArgStr} output={o => `${o}: ${o.length}`} />
<Test arg={myArgNo} output={o => `${o * 2}`} />
</>
);
interface MemoHelperFn {
<T extends string | number>(arg: TProps<T>): JSX.Element;
}
const MemoTest: MemoHelperFn = React.memo(Test);
const WithMemo = (
<>
<MemoTest arg={myArgStr} output={o => `${o}: ${o.length}`} />
<MemoTest arg={myArgNo} output={o => `${o * 2}`} />
</>
);
// Below fail as expected
const FailsWithoutMemo = (
<>
<Test arg={myArgNo} output={o => `${o}: ${o.length}`} />
<Test arg={myArgStr} output={o => `${o * 2}`} />
</>
);
const FailsWithMemo = (
<>
<MemoTest arg={myArgNo} output={o => `${o}: ${o.length}`} />
<MemoTest arg={myArgStr} output={o => `${o * 2}`} />
</>
);
有没有更优雅的想法来解决这个问题?
From https://stackoverflow.com/a/60170425/1747471 https://stackoverflow.com/a/60170425/1747471
interface ISomeComponentWithGenericsProps<T> { value: T; }
function SomeComponentWithGenerics<T>(props: ISomeComponentWithGenericsProps<T>) {
return <span>{props.value}</span>;
}
export default React.memo(SomeComponentWithGenerics) as typeof SomeComponentWithGenerics;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)