typescript 打字稿:TS7006:参数“xxx”隐式具有“任何”类型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43064221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Typescript: TS7006: Parameter 'xxx' implicitly has an 'any' type
提问by Diullei
In testing my UserRouter, I am using a json file
在测试我的 UserRouter 时,我使用了一个 json 文件
data.json
数据.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"
]
},
{
...
}
]
Building my app, I get the following TS error
构建我的应用程序,我收到以下 TS 错误
ERROR in ...../UserRouter.ts
(30,27): error TS7006: Parameter 'user' implicitly has an 'any' type.
UserRouter.ts
用户路由器.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;
回答by Diullei
You are using the --noImplicitAny
and TypeScript don't know about the type of Users
object. In this case, you need to explicitly define the user
type.
您正在使用--noImplicitAny
并且 TypeScript 不知道Users
对象的类型。在这种情况下,您需要明确定义user
类型。
change this line:
改变这一行:
let user = Users.find(user => user.id === query);
for this:
为了这:
let user = Users.find((user: any) => user.id === query);
// use "any" or someother interface to type this argument
Or define the type of your Users
object:
或者定义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');
//...
回答by st_ahmed
In your tsconfig.json
file set the parameter "noImplicitAny": false
under compilerOptions
to get rid of this error.
在您的tsconfig.json
文件中设置的参数"noImplicitAny": false
下compilerOptions
摆脱这种错误的。
回答by Jeff Eastman
I encounted this error and found that it was because the "strict" parameter was set to true in the tsconfig.json file. Just set it "false" (obviously). In my case I had generated the tsconfig file from the cmd prompt and simply missed the "strict" parameter, which was located further down in the file.
我遇到了这个错误,发现是因为tsconfig.json文件中的“strict”参数设置为true。只需将其设置为“false”(显然)。就我而言,我从 cmd 提示符生成了 tsconfig 文件,只是错过了位于文件更下方的“strict”参数。
回答by Sunali Bandara
if you get an error as Parameter 'element' implicitly has an 'any' type.Vetur(7006)in vueJs
如果你得到一个错误,因为参数 'element'在 vueJs 中隐式有一个 'any' type.Vetur(7006)
with the error:
有错误:
exportColumns.forEach(element=> {
if (element.command !== undefined) {
let d = element.command.findIndex(x => x.name === "destroy");
you can fixed it by defining thoes variables as any as follow.
您可以通过如下定义 thoes 变量来修复它。
corrected code:
更正的代码:
exportColumns.forEach((element: any) => {
if (element.command !== undefined) {
let d = element.command.findIndex((x: any) => x.name === "destroy");
回答by ford04
Minimal error reproduction
最小的错误再现
export const users = require('../data'); // presumes @types/node are installed
const foundUser = users.find(user => user.id === 42);
// error: Parameter 'user' implicitly has an 'any' type.ts(7006)
Recommended solution: --resolveJsonModule
推荐解决方案: --resolveJsonModule
您的案例最简单的方法是使用 --resolveJsonModule
--resolveJsonModule
编译器选项:
import users from "./data.json" // `import` instead of `require`
const foundUser = users.find(user => user.id === 42); // user is strongly typed, no `any`!
There are some alternatives for other cases than static JSON import.
除了静态 JSON 导入之外,还有一些其他情况的替代方案。
Option 1: Explicit user type (simple, no checks)
选项 1:显式用户类型(简单,无检查)
type User = { id: number; name: string /* and others */ }
const foundUser = users.find((user: User) => user.id === 42)
Option 2: Type guards (middleground)
选项 2:类型保护(中间)
Type guards类型保护是简单和强类型之间的一个很好的中间地带:function isUserArray(maybeUserArr: any): maybeUserArr is Array<User> {
return Array.isArray(maybeUserArr) && maybeUserArr.every(isUser)
}
function isUser(user: any): user is User {
return "id" in user && "name" in user
}
if (isUserArray(users)) {
const foundUser = users.find((user) => user.id === 42)
}
你甚至可以切换到 assertion functions断言函数(TS 3.7+) 来摆脱if
if
并抛出错误。
function assertIsUserArray(maybeUserArr: any): asserts maybeUserArr is Array<User> {
if(!isUserArray(maybeUserArr)) throw Error("wrong json type")
}
assertIsUserArray(users)
const foundUser = users.find((user) => user.id === 42) // works
Option 3: Runtime type system library (sophisticated)
选项 3:运行时类型系统库(复杂)
A runtime type check library like io-ts
or ts-runtime
can be integrated for more complex cases.
运行时类型检查库类似于io-ts
或ts-runtime
可以针对更复杂的情况进行集成。
Notrecommended solutions
不推荐的解决方案
noImplicitAny: false
noImplicitAny: false
破坏了类型系统的许多有用检查:
function add(s1, s2) { // s1,s2 implicitely get `any` type
return s1 * s2 // `any` type allows string multiplication and all sorts of types :(
}
add("foo", 42)
Also better provide an explicit User
type for user
. This will avoid propagating any
to inner layer types. Instead typing and validating is kept in the JSON processing code of the outer API layer.
也最好User
为user
. 这将避免传播any
到内层类型。相反,键入和验证保存在外部 API 层的 JSON 处理代码中。