typescript和mongoose:调用'save()时出现类型错误`

ncgqoxb0  于 2021-09-23  发布在  Java
关注(0)|答案(0)|浏览(200)

我有以下类型的mongoose模式:

type AnyToken =
  | GithubPermissionsPromptToken
  | SlackIssueFromReactionInteractionToken
  | SlackEditTemplateInteractionToken
  | SlackIssueFromMessageInteractionToken
  | CommentFromMessageInteractionToken
  | BaseToken<TokenType>;

type KnownTokenFromType<T extends TokenType> = Extract<AnyToken, { type: T }>;

export type TokenFromType<
  T extends TokenType
> = KnownTokenFromType<T> extends never ? BaseToken<T> : KnownTokenFromType<T>;

type TokenDocument<T extends TokenType = TokenType> = Document &
  (TokenType extends T ? BaseToken<T> : TokenFromType<T>);

interface TokenModel extends mongoose.Model<TokenDocument> {}

export const Token = mongoose.model<TokenDocument, TokenModel>('Token', schema);

如果我有代币

const token: TokenDocument<TokenType.SLACK_ISSUE_FROM_MESSAGE_INTERACTION | TokenType.COMMENT_FROM_MESSAGE_INTERACTION>

然后试着打电话 save() 在它上面,我得到以下ts错误:

TS2349: This expression is not callable.   

Each member of the union type '{ (options?: SaveOptions | undefined, fn?: ((err: any, product: Document & SlackIssueFromMessageInteractionToken) => void) | undefined): Promise<...>; (fn?: ((err: any, product: Document & SlackIssueFromMessageInteractionToken) => void) | undefined): Promise<...>; } | { ...; }' has signatures, but none of those signatures are compatible with each other.

我知道这是一个怪癖,但我想知道是否有办法解决它?
目前,我的解决方案是创建另一个函数

export function saveToken<T extends TokenType>(token: TokenDocument<T>) {
  return token.save();
}

但这显然并不理想。
任何帮助都将不胜感激,谢谢!

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题