下面的代码块从一个更大的应用程序中删除,以说明发生了什么...如果我忽略错误,则代码本身可以正常执行。只是类型提示不喜欢它,也不知道为什么。
不过,我确实认为与该Omit
类型有关。
出现此错误:
Argument of type '{ avatar: string; height: number; width: number; } & Pick<P & IInputProps, Exclude<keyof P, "firstName" | "lastName" | "avatar">>' is not assignable to parameter of type 'WrappedType<P>'.
Type '{ avatar: string; height: number; width: number; } & Pick<P & IInputProps, Exclude<keyof P, "firstName" | "lastName" | "avatar">>' is not assignable to type 'P'.
代码是(或gist):
type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
interface FunctionComponent<P = {}> {
(props: P, context?: any): string;
}
// Our component props types
interface IInputProps {
firstName: string;
lastName: string;
avatar: string;
}
interface ISubProps {
width: number;
height: number;
}
// The helper type that takes an abstract prop type, adds the downstream ISubProps + a type that's based on our IInputProps
type WrappedType<P extends object = {}> = P &
ISubProps &
Omit<IInputProps, 'firstName' | 'lastName'>;
type SubComponent<P> = FunctionComponent<WrappedType<P>>;
type WrappedComponent<P> = FunctionComponent<P & IInputProps>;
function factory<P extends object = {}>(
Component: SubComponent<P>,
): WrappedComponent<P> {
// The props here are of type P & IInputProps
return ({ lastName, firstName, avatar, ...rest }) => {
const restString = Object.entries(rest)
.map(([key, value]) => `${key}: ${value}`)
.join('\n');
// -- THIS BIT DOESNT WORK
// Component's types are ISubProps + IInputProps (-firstName, -lastName) + P
const componentResponse = Component(
{
avatar,
height: 10,
width: 20,
...rest,
},
);
// -- TO HERE
return `FirstName: ${firstName}\nLastName: ${lastName}\n${restString}\n\n--BEGIN--\n${componentResponse}\n--END--`;
};
}
// Example impl
const test = factory<{ foo: string }>(props => {
return `hello: ${props.foo}, you have the avatar of ${
props.avatar
} with height ${props.height} and width ${props.width}`;
})({
firstName: 'firstName',
lastName: 'lastName',
avatar: 'avatar',
foo: 'foo',
});
console.log(test);
答案 0 :(得分:2)
问题在于Typescript在数学上非常有限,它可以处理包含未绑定类型参数(例如P
)的映射和条件类型。
尽管对我们来说似乎很明显,但是编译器无法弄清楚,如果从lastName, firstName, avatar
中删除P & { firstName: string; lastName: string; avatar: string; }
,则会得到P
。只要参数P
在其中,编译器就不会尝试解析rest
的类型,而是将其余类型键入为Pick<P & IInputProps, Exclude<keyof P, "lastName" | "firstName" | "avatar">>
这里没有安全的方法来帮助编译器,您只需要使用类型断言来让编译器知道rest
将是P
const componentResponse = Component({
avatar,
height: 10,
width: 20,
...(rest as P),
});