【发布时间】:2019-12-16 06:06:34
【问题描述】:
为什么不能编译?
import * as fs from 'fs';
var folder: string = "c:/test1/test2/test3/";
fs.mkdirSync(folder, { recursive:true }); // the {object} shows an error
我是使用 MS Visual Studio 2019 社区的 TypeScript 新手。将工作的 Node.JS 代码转换为 TypeScript。我在项目启动时调用一个函数。此代码在 Node.JS 中有效,但在 TypeScript 中显示编译错误。
fs.mkdirSync(文件夹,{递归:真}); // {object} 不会编译。
我不明白为什么不允许我传递指定递归位的对象。目前在新手荒野游荡。建议将不胜感激。 当我将鼠标悬停在编译错误上时,我得到了这个弹出窗口:
(property) recursive: boolean
(TS) Argument of type '{ recursive: boolean }' is not assignable to parameter of type 'string | number'.
Type '{ recursive: boolean }' is not assignable to type 'number'.
似乎忽略了 MakeDirectoryOptions 的 fs.d.ts 定义:
到目前为止我做了什么:
1) 我搜索了驱动器 C: 并找到了 4 个 fs.d.ts 文件。每个都包含以下定义:
function mkdirSync(path: PathLike, options?: number | string | MakeDirectoryOptions | null): void;
export interface MakeDirectoryOptions {
/**
* Indicates whether parent folders should be created.
* @default false
*/
recursive?: boolean;
/**
* A file mode. If a string is passed, it is parsed as an octal integer. If not specified
* @default 0o777.
*/
mode?: number;
}
2) 我尝试修改 package.json 设置:
"devDependencies": {
"@types/node": "^8.0.14",
"typescript": "^3.2.2" // forcing this to use the latest 3.6.0
}
重现问题的代码: -----server.ts
import * as fs from 'fs';
//import fs = require("fs"); // does not work
//var fs = require("fs"); // compiles
var folder:string = "c:/test1/test2/test3/";
var result: string = "untested";
try {
// test for the existance of a folder
if (!fs.existsSync(folder)) {
// create the folder if found to not exist
fs.mkdirSync(folder, { recursive: true }); // { recursive: true } shows as compile error
result = "created";
}
else {
result = "exists already";
}
}catch(err) {
result = err.message;
}
import * as http from 'http';
var port: number | string = process.env.port || 1337
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Operation result: = ' + result + "\n");
}).listen(port);
-----package.json
{
"name": "trials",
"version": "0.0.0",
"description": "trials",
"main": "server.js",
"author": {
"name": ""
},
"scripts": {
"build": "tsc --build",
"clean": "tsc --build --clean"
},
"devDependencies": {
"@types/node": "^8.0.14",
"typescript": "^3.2.2"
}
}
-----tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"lib": ["es6"],
"sourceMap": true
},
"exclude": [
"node_modules"
]
}
-----代码结束
如果我更改“import * as fs from 'fs';”行至: var fs = 要求(“fs”); 一切都编译和工作 - 但我认为这是作弊?
似乎忽略了 MakeDirectoryOptions 的 fs.d.ts 定义:
function mkdirSync(path: PathLike, options?: number | string | MakeDirectoryOptions | null): void;
导出接口 MakeDirectoryOptions {etc....}
【问题讨论】:
标签: node.js typescript