我是Node.js的新手,现在正在学习一些基础知识。我稍后尝试使用一些打字稿代码转换为.js代码。
我编写了此简单代码进行测试
import * as fs from 'fs'
const argv = require('yargs')
.alias('f', 'filename')
.alias('c', 'content')
.demandOption('filename')
.demandOption('content')
.argv
fs.writeFile(argv.filename, argv.content, (error)=>{
if(error)
throw error
console.log(`File ${argv.filename} saved.`)
})
而且这很好。但是当我将行require('yargs')更改为import时,如下所示:
import * as fs from 'fs'
import * as yargs from 'yargs'
const argv = yargs
.alias('f', 'filename')
.alias('c', 'content')
.demandOption('filename')
.demandOption('content')
.argv
fs.writeFile(argv.filename, argv.content, (error)=>{
if(error)
throw error
console.log(`File ${argv.filename} saved.`)
})
我遇到此错误:
Argument of type 'unknown' is not assignable to parameter of type 'string | number | Buffer | URL'.
Type '{}' is missing the following properties from type 'URL': hash, host, hostname, href, and 9 more.ts(2345)
有人知道使用导致错误的模块/导入有什么区别吗?对于fs库,在此示例中,两种方法都可以正常工作。
您需要通过argv设置args的类型。尝试将您的核心更改为:
const argv = yargs
.option('filename', {
alias: 'f',
demandOption: true,
describe: 'Nome do arquivo',
type: 'string'
})
.option('content', {
alias: 'c',
demandOption: true,
describe: 'Conteudo',
type: 'string'
})
.argv