javascript - 为什么 TypeScript 在 getCurrenUlr() 返回 `any` 时提示参数具有隐式类型 `Promise<string>` ?

标签 javascript selenium-webdriver typescript protractor

我正在使用 protractor 4.x使用 typescript 。使用 typescript 2.0 ,编译器在以下测试中提示:

it('should have url', done=>{
  browser.getCurrentUrl().then((x)=>{
    // do something with x
  })
})

它说:error TS7006: Parameter 'x' implicitly has an 'any' type. 是的,我知道我可以在文件 tsconfig.json 中关闭它或明确设置类型,但我真正的问题是为什么?

当我将鼠标悬停在 browser.getCurrentUrl() 上时它清楚地写着 (property) Webdriver.getCurrentUrl: () => webdriver.promise.Promise<string>所以,x 应该隐式地属于 string 类型

重现步骤

  • 克隆https://github.com/angular/protractor
  • follow instructions for running examples
  • 在示例文件夹中,设置noImplicitAnytruetsconfig.json
  • spec.ts 中添加上面的测试文件
  • 尝试编译。

tsconfig.json (直接来自 Protractor ):

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "moduleResolution": "node",
        "sourceMap": false,
        "declaration": false,
        "noImplicitAny": true,
        "outDir": "tmp",
        "types": ["node", "jasmine"]
    },
    "exclude": [
        "node_modules",
        "asyncAwait",
        "plugins.ts"
    ]
}

最佳答案

这样做的原因是因为你需要显式给参数x一个类型:

it('should have url', done=>{
  browser.getCurrentUrl().then((x: string)=>{
    // do something with x
  })
})

关于javascript - 为什么 TypeScript 在 getCurrenUlr() 返回 `any` 时提示参数具有隐式类型 `Promise<string>` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39857881/

相关文章:

typescript - React Native with Typescript 2.8 - 无法重新声明 block 作用域变量 'console'

javascript - Angular(Javascript)如何控制mousemove事件的速度?

node.js - Nodejs promise 捕获 "hell"然后使用 sequelize orm

c# - 在滚动 SPA 时,父 div 向上移动太远后,WebDriver 将子 div 报告为 "Not Visible"

css - selenium 2.0 中 css 和等效 xpath 之间的区别

javascript - 使用 lodash 将对象数组转换为对象

javascript - 如何将图像从 native react 发送到 native 模块?

c# - 带有 NUnit 的 SpecFlow : SetUp method runs twice

javascript - 在 HTML 文件中使用 JavaScript 在后台添加计时事件

Javascript 删除元素样式