You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在TypeScript中获取未知导入函数的类型/接口?

如何指定Node.js加密函数返回的类型?
  • 首先确保安装Node.js的类型定义包,它包含了所有内置模块的类型:

    npm install @types/node --save-dev
    
  • 方法一:直接从crypto模块导入Cipher类型
    官方类型定义已经将Cipher接口暴露出来,可直接导入使用:

    import { createCipheriv, Cipher } from 'crypto';
    
    // 假设key和iv已提前定义
    const cipher: Cipher = createCipheriv('aes-256-cbc', key, iv);
    
  • 方法二:用ReturnType工具类型推导返回类型
    如果不想显式导入Cipher,可以借助TypeScript的工具类型自动提取函数返回类型:

    import { createCipheriv } from 'crypto';
    
    // 自动推导类型
    const cipher = createCipheriv('aes-256-cbc', key, iv);
    
    // 或者显式指定类型
    const cipher: ReturnType<typeof createCipheriv> = createCipheriv('aes-256-cbc', key, iv);
    

注意:@types/node的版本尽量和你使用的Node.js主版本保持一致,避免出现类型不匹配的问题。

内容的提问来源于stack exchange,提问作者Marten

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 22:20:30