[英]Element implicitly has an 'any' type because type 'xxx' has no index signature
I encounter two case about this problem when I try to refactor a es6 project in typescript, and one is about Object.keys()
and the other is about import * as xxx
. 当我尝试在打字稿中重构es6项目时遇到两种有关此问题的情况,一种是关于
Object.keys()
,另一种是关于import * as xxx
。
Case 1: 情况1:
const SUPPORTED_VALUES = {
min_s: 'Mininum similarity',
max_rc: 'Maximum result count'
}
const UNSUPPORTED_MSG =
'Configurable values:\n' +
Object.keys(SUPPORTED_VALUES)
.map(k => `${k}: ${SUPPORTED_VALUES[k]}`)
.join('\n')
The k
in the map
is guaranteed to be a key in SUPPORTED_VALUES
, but typescript compiler doesn't know about this. map
的k
保证是SUPPORTED_VALUES
的键,但是Typescript编译器对此一无所知。 How should I fix this without disabling noImplicitAny
? 如何在不禁用
noImplicitAny
情况下解决此noImplicitAny
?
Case 2: 情况2:
I have a file called cmd.ts
: 我有一个名为
cmd.ts
的文件:
export async function cmd1(args){}
export async function cmd2(args){}
It is used is another file like this: 使用的是另一个这样的文件:
import * as cmdHandlers from './cmd'
// some code...
if (cmd in cmdHandlers) {
await cmdHandlers[cmd](bot, msg, ...args)
}
This is also guaranteed that cmd
exists in cmdHandlers
, but typescript compiler can't handle this. 这也可以确保
cmdHandlers
存在cmd
,但是打字稿编译器无法处理此问题。
In case 1, you need define exactly type for SUPPORTED_VALUES
like {[key: string]: string}
在情况1中,您需要为
SUPPORTED_VALUES
准确定义类型,例如{[key: string]: string}
const SUPPORTED_VALUES: {[key: string]: string} = {
min_s: 'Minimum similarity',
max_rc: 'Maximum result count'
}
const UNSUPPORTED_MSG =
'Configurable values:\n' +
Object.keys(SUPPORTED_VALUES)
.map(k => `${k}: ${SUPPORTED_VALUES[k]}`)
.join('\n')
Case 2, The same case 1, cmd
can be anything, but cmdHandlers
only includes cmd1
and cmd2
. 情况2,与情况1相同,
cmd
可以是任何东西,但cmdHandlers
仅包括cmd1
和cmd2
。 You can define your type for cmd.ts
module to make cmdHandlers
is a object with any property name. 您可以为
cmd.ts
模块定义类型,以使cmdHandlers
是具有任何属性名称的对象。
I think it is ok, because you have a condition before call a function 我认为可以,因为在调用函数之前您有条件
// cmd.ts // cmd.ts
async function cmd1(...args: any) { }
async function cmd2(...args: any) { }
const myExport: { [key: string]: (...args: any) => void } = {
cmd1,
cmd2,
}
export default myExport;
// //
import cmdHandlers from './cmd'
// some code...
if (cmd in cmdHandlers) {
await cmdHandlers[cmd](bot, msg, ...args)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.