如何扩展 DefinitelyTyped 社区定义的函数声明?

How to extend function declaration defined by DefinitelyTyped community?

我正在使用 jsonwebtoken library within TypeScript project. Together with this library, I've imported @types/jsonwebtoken 库来提供类型。 在这个库中 jsonwebtoken 的函数 verify declared as following:

export function verify(
  token: string, 
  secretOrPublicKey: Secret, 
  options?: VerifyOptions
): object | string;

但我想具体说明它是哪个对象 returns,而不仅仅是 object | string 例如,由以下接口定义的对象:

export interface DecodedJwtToken {
  userId: string;
  primaryEmail: string;
}

如何在我的项目中实现它?是否可以不进行类型转换,即

const decodedToken: DecodedJwtToken = verify(token, JWT_PRIVATE_KEY) as DecodedJwtToken;

提前致谢。

您要找的是module augmentation:

import { Secret, VerifyOptions } from 'jsonwebtoken';

export interface DecodedJwtToken {
    userId: string;
    primaryEmail: string;
}

declare module 'jsonwebtoken' {
    function verify(token: string, secretOrPublicKey: Secret, options?: VerifyOptions): DecodedJwtToken;
}