在打字稿中
const func = (str: string) => {
const strToNumber = {
account: 0,
goals: 1,
metrics: 2,
};
const number = strToNumber?.[str] || 0;
};
给出以下错误:
元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“{ account: number; 目标:数量;指标:数字;}'。在“{ account: number;”类型上找不到带有“string”类型参数的索引签名;目标:数量;指标:数字;}'。
我有点理解为什么它会给出这个错误,但同时我没有看到代码有任何问题,因为我使用的是可选链接,任何错误的值都会回退到 0。
我应该怎么做才能不出现此错误?有没有不涉及使用“as”或“@ts-ignore”的方法?
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"baseUrl": "./",
"paths": {
"@components/*": [
"components/*"
],
"@lib/*": [
"lib/*"
],
"@utils/*": [
"utils/*"
],
"@public/*": [
"public/*"
],
"@types/*": [
"types/*"
]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
"tailwind.config.js"
],
"exclude": [
"node_modules"
]
}