TypeScript提示Parameter 'array' implicitly has 'any' type是什么意思?
错误原因
这是TypeScript的类型检查触发的报错,和milkResponses数组的定义无关:
- 你未给
randomArrayShuffle的入参array声明显式类型,TypeScript无法推断类型时会默认将其标记为any类型 - 如果你的项目
tsconfig.json中开启了noImplicitAny编译规则,就会抛出「Parameter 'array' implicitly has 'any' type」的错误
修复方案
方案1:限定为字符串数组类型
如果该函数仅用于打乱字符串数组,直接给入参添加string[]类型声明即可:
var milkResponses: string[] = ["I like milk", "mmmm"]; // 给array参数显式声明字符串数组类型 function randomArrayShuffle(array: string[]) { var currentIndex = array.length, temporaryValue, randomIndex; while (0 !== currentIndex) { randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; }
方案2:泛型通用写法
如果需要函数支持打乱任意类型的数组,使用泛型声明适配不同数组类型:
// T为泛型参数,函数可接收任意类型的数组,返回值类型和入参数组类型一致 function randomArrayShuffle<T>(array: T[]): T[] { var currentIndex = array.length, temporaryValue, randomIndex; while (0 !== currentIndex) { randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; }
临时绕过方案(不推荐)
如果不需要严格的类型检查,可以修改项目tsconfig.json的编译配置,关闭隐式any校验:
{ "compilerOptions": { "noImplicitAny": false } }
该方案会失去TypeScript的部分类型校验能力,仅建议临时调试时使用。
内容的提问来源于stack exchange,提问作者TheoChow
相关产品推荐
相关产品推荐

