【发布时间】:2021-08-14 18:26:04
【问题描述】:
当我返回的结果应该符合函数的预期类型时,我不断收到could be instantiated with a different subtype of constraint 错误,我无法理解我做错了什么。这是我的代码,删除了所有不相关的细节:
type User = { }
interface BasePageProps {
user: User
}
type GetServerSidePropsResult<P> =
| { props: P }
type PropsWithUser = <TProps extends BasePageProps>(
callback: (user: User) => Promise<Omit<TProps, 'user'>>
) => Promise<GetServerSidePropsResult<TProps>>
export const testFunc: PropsWithUser = async (callback) => {
const user = {}
return { props: {
user,
...(await callback(user))
} }
}
这是我得到的错误:
'{ 用户:{}; } & Omit
' 可分配给类型为“TProps”的约束,但可以使用约束“BasePageProps”的不同子类型来实例化“TProps”。
Here's this example on TS Playground.
为什么用不同子类型实例化的潜在TProps 是个问题?我该如何解决?
P.S.:您可能会注意到这些类型取自 Next.js。不过这个问题跟 Next.js 本身没有关系,所以请不要给这个问题打标签。
【问题讨论】:
标签: typescript generics