首页 > 解决方案 > 如何扩展DefinitelyTyped社区定义的函数声明?

问题描述

我在 TypeScript 项目中使用jsonwebtoken库。连同这个库,我导入了@types/jsonwebtoken库来提供类型。在这个库中 jsonwebtoken 的函数verify 声明如下

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

但是我想指定它返回的确切对象,而不仅仅是object | string例如由以下接口定义的对象:

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

我怎样才能在我的项目中实现它?可以不用类型转换就可以完成,即

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

先感谢您。

标签: typescripttypesdefinitelytyped

解决方案


您正在寻找的是模块扩充

import { Secret, VerifyOptions } from 'jsonwebtoken';

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

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

推荐阅读