Node.js 如何将VSCode Intellisense与transpiled TypeScript NodeJS类一起使用
因此,我有一个TypeScricpt Nodejs控制器,我使用以下脚本传输了TypeScript:Node.js 如何将VSCode Intellisense与transpiled TypeScript NodeJS类一起使用,node.js,typescript,intellisense,Node.js,Typescript,Intellisense,因此,我有一个TypeScricpt Nodejs控制器,我使用以下脚本传输了TypeScript: "scripts": { "build": "npm run clean && mkdir dist && tsc -p .", "clean": "rm -rf dist" }, 打字稿被传输了,但我面临的问题是。现在,当我测试传输的源代码时,我
"scripts": {
"build": "npm run clean && mkdir dist && tsc -p .",
"clean": "rm -rf dist"
},
打字稿被传输了,但我面临的问题是。现在,当我测试传输的源代码时,我期待以下内容:
instanceObj.
编写任何东西之前,应该使用内置类方法提示我VS code不知道参数是什么,因为您没有任何类型定义,例如,在TypeScript synax中描述接口的.d.ts文件。
- 但后来我意识到,我有所有这些,但仍然没有按预期工作
import { Document, Model } from "mongoose";
import { Request, Response } from "express";
interface Auth {
SignUp(request: Request, response: Response): Response;
Login(request: Request, response: Response): Reponse;
}
declare class AuthController implements Auth {
userModel: Model<Document>;
userSession: Document;
hashRounds: number;
mailTransporterUser: string;
mailTransporterPass: string;
passwordLength: number;
constructor(userModel: Model<Document>, userSessions: Document, hashRounds: number, mailTransporterUser: string, mailTransporterPass: string, passwordLength: number);
SignUp(request: Request, response: Response): Response<any>;
Login(request: Request, response: Response): Response<any>;
}
export default AuthController;
//# sourceMappingURL=Auth.d.ts.map
import AuthController from "./Auth";
export default AuthController;
//# sourceMappingURL=index.d.ts.map
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es5" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */,
"module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */,
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
"declaration": true /* Generates corresponding '.d.ts' file. */,
"declarationMap": true /* Generates a sourcemap for each corresponding '.d.ts' file. */,
"sourceMap": true /* Generates corresponding '.map' file. */,
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "dist" /* Redirect output structure to the directory. */,
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true /* Enable all strict type-checking options. */,
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"skipLibCheck": true /* Skip type checking of declaration files. */,
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
},
"include": ["src"]
}
我认为这是调用类或对象时的标准代码行为(我将省略代码中的登录,因为我避免使代码变长,但仅使用一种方法,我的问题应该是可重现的)
下面的代码是TypeScript类:
interface Auth {
SignUp(request: Request, response: Response): Response;
Login(request: Request, response: Response): Response;
}
class AuthController implements Auth {
userModel: Model<Document>;
userSession: Document;
hashRounds: number;
mailTransporterUser: string;
mailTransporterPass: string;
passwordLength: number;
constructor(
userModel: Model<Document>,
userSessions: Document,
hashRounds: number,
mailTransporterUser: string,
mailTransporterPass: string,
passwordLength: number
) {
this.userModel = userModel;
this.userSession = userSessions;
this.hashRounds = hashRounds || 15;
this.mailTransporterUser = mailTransporterUser;
this.mailTransporterPass = mailTransporterPass;
this.passwordLength = passwordLength || 8;
}
SignUp(request: Request, response: Response) {
const form: Formidable.IncomingForm = new Formidable.IncomingForm();
try {
form.parse(request, async (error, fields, files) => {
if (error) {
return response
.status(500)
.json({ msg: "Network Error: Failed to sign user up" });
}
const { username, email, password, verifiedPassword } = fields;
if (!username || !email || !password || !verifiedPassword) {
return response.status(400).json({ msg: "All fields are required" });
}
if (password.length < this.passwordLength) {
return response.status(400).json({
msg: `Password has to be at least ${this.passwordLength} characters long`,
});
}
if (password !== verifiedPassword) {
return response.status(400).json({ msg: "Password's do not match" });
}
const isUserAlreadyExisting = await this.userModel.findOne({
email: email,
});
if (!isUserAlreadyExisting) {
return response
.status(400)
.json({ msg: "Account with this email already exist" });
}
const salt: string = await Bcrypt.genSalt(this.hashRounds);
const hashedPassword: string = await Bcrypt.hash(password, salt);
const newUser = new this.userModel({
username: username,
email: email,
password: hashedPassword,
});
const savedUser = await newUser.save();
});
return response.status(201).json({ msg: "Account successfully created" });
} catch (error) {
console.error(error);
return response
.status(500)
.json({ msg: "Network Error: Failed to signup user" });
}
}
}
希望在这个问题上得到帮助,我真的不知道我在类文件中的这个问题哪里出了问题:
类AuthController实现了Auth{
,你的意思是在这个前面写导出默认值
,您的意思是像const AuthController=require(“/Auth”)
?为什么不使用标准的import AuthController from“/Auth”
,当我使用require intellisense时无法给出提示,但使用import时效果很好。我相信这是因为require是动态的,所以它在运行时才知道类型。@Krispies对于我在问题中提到的第一个问题,我省略了某些代码方法,以避免这方面的冗长代码,我也省略了ed toexport defualt
…尝试同时使用ES6导入和ES5,但保持不变没有intellisense,我不确定,但我相信更多的是我这边的TypeScript配置,但我无法指出有什么错你能将整个项目放在github上吗?你可以省略任何敏感信息,而且.d.t都生成正确吗?你应该ldn不需要在问题中发布这些内容。@Krispies很抱歉延迟了一段时间的回复,所以你不会相信解决这个问题的方法就是将类型
添加到package.json
并将其指向我的index.d.ts
文件,然后类文件中的一切都开始工作:类AuthController实现Auth{
,你的意思是在前面写export default
吗?当你说“当我需要这个类时”,你的意思是像const AuthController=require(“/Auth”)
?为什么不使用标准的从“/Auth”导入AuthController呢
,当我使用require intellisense时无法给出提示,但使用import时效果很好。我相信这是因为require是动态的,所以它在运行时才知道类型。@Krispies对于我在问题中提到的第一个问题,我省略了某些代码方法,以避免这方面的冗长代码,我也省略了ed toexport defualt
…尝试同时使用ES6导入和ES5,但保持不变没有intellisense,我不确定,但我相信更多的是我这边的TypeScript配置,但我无法指出有什么错你能将整个项目放在github上吗?你可以省略任何敏感信息,而且.d.t都生成正确吗?你应该ldn不需要在问题中发布这些内容。@Krispies很抱歉迟了一点回复,所以你不会相信解决这个问题的方法就是将类型
添加到package.json
并将其指向我的index.d.ts
文件,然后一切都开始工作了