问题描述
我的短毛猫说我不应该在TS中使用object作为类型。但是,我正在使用的库要求扩展对象的通用类型。
因此,我正在使用如下所示的库编写通用组件:
const testRef = React.useRef<HTMLdivelement>(null);
React.useEffect(() => {
if (testRef.current) {
doSomething();
}
},[testRef.current]);
由于棉短袜的抱怨,我试图将其切换到
const Component = <T extends object>(props: CustomProps<T>): React Element => etc.
但是,如果我再做这样的事情:
const Component = <T extends Record<string,unkNown>>(props: CustomProps<T>): React Element => etc.
TS表示MyInterface不满足约束Record
interface MyInterface {
something: string;
goes: number;
here: string;
}
const CallerComponent = () => Component<MyInterface> />
我宁愿不必遍历整个代码库,而是将其添加到每个接口中,因此,很高兴知道是否有一种方法可以在我说T一定是对象的地方键入它。
在此先感谢您的帮助。
解决方法
我遇到了同样的问题,发现您可以使用 type
而不是 interface
来声明您的对象并解决了它。
在你的情况下是:
type MyInterface = {
something: string
goes: number
here: string
}
,
我认为可以这样使用
interface MyInterface extends Record<any,any>