【问题标题】:How to extend function declaration defined by DefinitelyTyped community?如何扩展DefinitelyTyped社区定义的函数声明?
【发布时间】:2020-04-08 04:44:42
【问题描述】:

我在 TypeScript 项目中使用 jsonwebtoken 库。连同这个库,我已经导入了@types/jsonwebtoken 库来提供类型。 在这个库中jsonwebtoken的函数verifydeclared as following:

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;

提前谢谢你。

【问题讨论】:

    标签: typescript types definitelytyped


    【解决方案1】:

    你要找的是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;
    }
    

    【讨论】:

    • 谢谢,这正是我一直在寻找的
    猜你喜欢
    • 1970-01-01
    • 2019-02-10
    • 1970-01-01
    • 2017-02-12
    • 1970-01-01
    • 1970-01-01
    • 2020-10-07
    • 1970-01-01
    相关资源
    最近更新 更多