空对象{}不是typescript中的类型{}
我有下面的helper方法,它返回一个包装的react组件空对象{}不是typescript中的类型{},typescript,Typescript,我有下面的helper方法,它返回一个包装的react组件 export function wrapComponentInContext<T extends object = {}>( Comp: React.FunctionComponent<T>, props: T = {}) { // ERROR: Type '{}' is not assignable to type 'T' const mockSetter = jest.fn(() =>
export function wrapComponentInContext<T extends object = {}>(
Comp: React.FunctionComponent<T>,
props: T = {}) { // ERROR: Type '{}' is not assignable to type 'T'
const mockSetter = jest.fn(() => { });
const mockContext: ContextDefaultValue = ["context", mockSetter];
return (
<Provider value={mockContext}>
<Comp {...props}/>
</Provider>
);
}
导出函数wrapComponentInContext(
组件:React.function组件,
props:T={}{//错误:类型{}不可分配给类型“T”
const mockSetter=jest.fn(()=>{});
const mockContext:ContextDefaultValue=[“context”,mockSetter];
返回(
);
}
如果没有提供参数,我希望默认为空对象
这里有一个更简单的例子
因此,似乎空对象的类型不是令人困惑的{}
为什么通用函数需要对传递到函数中的任何可能的
T
有效T扩展对象
意味着T
可以是任何对象类型,因此它可以是{foo:string}
,并且{}
不是此类型的有效默认值
类型参数的默认类型与参数的默认类型没有任何关联。您可以使用显式类型参数而不使用默认值进行调用,从而在传入的默认值{}
和T
之间产生冲突。或者,您可以忽略默认值,并使用所需的道具传入组件:
declare function comp(o: { p: string }): void;
wrapComponentInContext(comp)
您可以使用类型断言强制{}
进入T
:
export function wrapComponentInContext<T extends object = {}>(Comp: React.FunctionComponent<T>, props: T = {} as T) {
}
declare function compOptional(o: { p?: string }): void;
declare function comp(o: { p: string }): void;
export function wrapComponentInContext<T>(Comp: React.FunctionComponent<T> & ({} extends T ? {} : "Provide default props as component requires some"))
export function wrapComponentInContext<T extends object>(Comp: React.FunctionComponent<T>, props: T)
export function wrapComponentInContext<T extends object = {}>(Comp: React.FunctionComponent<T>, props: T = {} as T) {
}
wrapComponentInContext(comp) // Type '(o: { p: string; }) => void' is not assignable to type '"Provide default props as component requires some"'.
wrapComponentInContext(compOptional)
wrapComponentInContext(comp, { p: "" })