TypeScript中使用youtube-dl-exec报“不可调用”错误的解决方法
解决youtube-dl-exec在TypeScript中无法调用的类型错误
问题场景
代码可正常编译运行,但TypeScript提示类型错误,不想用//@ts-ignore消除:
This expression is not callable.
Type typeof import(...) has no call signatures.
代码示例
import youtubeDl from 'youtube-dl-exec'; const run = async () => { const output = await youtubeDl('https://www.youtube.com/watch?v=6xKWiCMKKJg', { dumpSingleJson: true, noCheckCertificates: true, noWarnings: true, extractAudio: true, addHeader: ['referer:youtube.com', 'user-agent:googlebot'], }); console.log(output); }; run();
tsconfig配置
{ "$schema": "https://json.schemastore.org/tsconfig", "extends": "@tsconfig/strictest/tsconfig.json", "compilerOptions": { "lib": ["es2023"], "module": "node16", "target": "es2022", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "moduleResolution": "node16", "preserveWatchOutput": true, "sourceMap": true, "forceConsistentCasingInFileNames": true, "useUnknownInCatchVariables": true, "noUnusedLocals": true, "noImplicitReturns": true, "outDir": "./dist", "resolveJsonModule": true, }, "ts-node": { "esm": true, } }
错误信息
This expression is not callable. Type typeof import('/Users/***/WORK/WLOS/***/***-video-translator-back-end-2/node_modules/youtube-dl-exec/src/index') has no call signatures.
解决方案
这是Node16模块解析模式下,ES模块与CommonJS模块交互时的类型导出问题,可通过以下方式解决:
方式一:调整导入方式
修改导入语句,显式获取默认导出的函数:
import * as youtubeDlModule from 'youtube-dl-exec'; const youtubeDl = youtubeDlModule.default;
之后原调用逻辑无需修改,TypeScript会正确识别函数类型。
方式二:添加类型断言
用库自带的类型定义做断言,避免使用any:
import youtubeDl from 'youtube-dl-exec'; import type { Options } from 'youtube-dl-exec'; const run = async () => { const output = await (youtubeDl as unknown as (url: string, options: Options) => Promise<any>)( 'https://www.youtube.com/watch?v=6xKWiCMKKJg', { dumpSingleJson: true, noCheckCertificates: true, noWarnings: true, extractAudio: true, addHeader: ['referer:youtube.com', 'user-agent:googlebot'], } ); console.log(output); }; run();
方式三:修改tsconfig配置
若项目允许,将moduleResolution改为bundler,适配ES模块导出逻辑:
"moduleResolution": "bundler"
无需修改代码,TypeScript即可正确识别默认导出的函数类型。
内容的提问来源于stack exchange,提问作者mp3por
相关产品推荐
相关产品推荐

