在测试我的UserRouter时,我使用了一个json文件
data.json
[
{
"id": 1,
"name": "Luke Cage",
"aliases": ["Carl Lucas", "Power Man", "Mr. Bulletproof", "Hero for Hire"],
"occupation": "bartender",
"gender": "male",
"height": {
"ft": 6,
"in": 3
},
"hair": "bald",
"eyes": "brown",
"powers": [
"strength",
"durability",
"healing"
]
},
{
...
}
]
构建我的应用程序时,我会得到以下TS错误
ERROR in ...../UserRouter.ts
(30,27): error TS7006: Parameter 'user' implicitly has an 'any' type.
UserRouter.ts
import {Router, Request, Response, NextFunction} from 'express';
const Users = require('../data');
export class UserRouter {
router: Router;
constructor() {
...
}
/**
* GET one User by id
*/
public getOne(req: Request, res: Response, _next: NextFunction) {
let query = parseInt(req.params.id);
/*[30]->*/let user = Users.find(user => user.id === query);
if (user) {
res.status(200)
.send({
message: 'Success',
status: res.status,
user
});
}
else {
res.status(404)
.send({
message: 'No User found with the given id.',
status: res.status
});
}
}
}
const userRouter = new UserRouter().router;
export default userRouter;
发布于 2017-03-28 13:24:45
您使用的是--noImplicitAny
,而TypeScript不知道Users
对象的类型。在这种情况下,您需要显式地定义user
类型。
更改这一行:
let user = Users.find(user => user.id === query);
对此:
let user = Users.find((user: any) => user.id === query);
// use "any" or some other interface to type this argument
或者定义Users
对象的类型:
//...
interface User {
id: number;
name: string;
aliases: string[];
occupation: string;
gender: string;
height: {ft: number; in: number;}
hair: string;
eyes: string;
powers: string[]
}
//...
const Users = <User[]>require('../data');
//...
发布于 2018-10-08 21:15:20
在tsconfig.json
文件中,在compilerOptions
下设置参数"noImplicitAny": false
以消除此错误。
发布于 2021-06-09 09:51:00
在您的compilerOptions
部分的tsconfig.json
文件中进行这些更改--这对我来说是有效的
"noImplicitAny": false
不需要设置
"strict":false
请稍等1到2分钟,一些pcs机的编译速度很慢
https://stackoverflow.com/questions/43064221
复制相似问题