以下代码块是从一个更大的应用程序中提取出来的,以说明发生了什么问题...如果我忽略错误,代码本身执行得很好。只是类型提示不喜欢它,不知道为什么。
不过,我确实相信这与 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);
最佳答案
问题在于 Typescript 在包含未绑定(bind)类型参数的映射类型和条件类型(例如您的情况下的 P
)上可以执行的数学运算非常有限。
虽然这对我们来说似乎很明显,但如果您删除 lastName, firstName, avatar
,编译器将无法识别。来自 P & { firstName: string; lastName: string; avatar: string; }
你得到 P
.只要参数P
在那里,编译器不会尝试解析 rest
的类型相反,它会将 rest 输入为 Pick<P & IInputProps, Exclude<keyof P, "lastName" | "firstName" | "avatar">>
这里没有安全的方法来帮助编译器,您只需要使用类型断言让编译器知道 rest
将是 P
const componentResponse = Component({
avatar,
height: 10,
width: 20,
...(rest as P),
});
关于typescript - 类型参数不可分配给类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53951631/