@types/jquery 从 2.0.47 升级到 3.2.11 的问题

issue with @types/jquery upgrading from 2.0.47 to 3.2.11

使用@types/jquery 2.0.47 有一段时间了 w/out 任何问题。我已尝试升级到 3.2.11,但现在当我构建 visual studio 解决方案时根本无法编译任何内容。我遇到了很多错误,虽然不完全相同,但绝对相关。我正在使用打字稿 2.4。例如:

构建:属性 'length' 在类型 'string | number | string[]' 上不存在。

if ($("#txtSelPrj") && $("#txtSelPrj").val().length > 0) ...

构建:属性 'startsWith' 在类型 'string | number | string[]'

上不存在
var cityVal = $("#City").val();
if (cityVal.startsWith('MyCity')) ...

等等。下面是我的 tsconfig.json 。为什么会发生这种情况,我是否遗漏了什么?

{
  "compilerOptions": {
    "module": "es2015",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "noEmitHelpers": true,
    "noEmitOnError": true,
    "noImplicitAny": false,
    "allowUnusedLabels": true,
    "target": "es5",
    "sourceMap": true,
    "strictNullChecks": false,
    "removeComments": true,
    "baseUrl": "./scripts",
    "declaration": false,
    "paths": {
    },
    "lib": [
      "dom",
      "es6",
      "scripthost",
      "es5",
      "es2015",
      "es2015.promise",
      "es2015.iterable"
    ],
    "types": [
      "angular-ui-bootstrap",
      "angular",
      "autolinker",
      "bootbox",
      "bootstrap-notify",
      "bootstrap",
      "bootstrap-switch",
      "cldrjs",
      "globalize",
      "googlemaps",
      "google.analytics",
      "imagesloaded",
      "jquery.blockui",
      "jquery.bootstrap.wizard",
      "jquery",
      "jqueryui",
      "jquery.validation",
      "jsts",
      "kendo-ui",
      "masonry-layout",
      "qtip2",
      "signalr",
      "urijs",
      "moment"
    ]
  },
  "exclude": [
    "node_modules",
    "bower_components",
    "build"
  ],
  "typeRoots": [
    "node_modules/@types",
    "node_modules/moment"
  ],
  "awesomeTypescriptLoaderOptions": {
    "useBabel": true,
    "useCache": true
  },
  "compileOnSave": true,
  "buildOnSave": true 
}

查看文档:http://api.jquery.com/val/ JQuery 3 returns number 来自对 val() 的调用,如下所示:

因此 v3 的当前 @types/jquery 是对文档的准确反映。因此错误:

Build:Property 'length' does not exist on type 'string | number | string[]'.

绝对正确,因为 lengthnumber 上不存在。

修复

你可以做一个类型保护来确保它是一个字符串,例如typeof : https://basarat.gitbooks.io/typescript/docs/types/typeGuard.html

或者,如果您很懒惰(并且喜欢玩),请使用类型断言:https://basarat.gitbooks.io/typescript/docs/types/type-assertion.html