Karma或TypeScript编译器告诉我类型'String'不存在属性'padStart'

时间:2019-03-27 01:05:49

标签: angular typescript unit-testing karma-runner

我有一个Angular 7项目,其中lib = es2015和target = es2015,并且Angular-CLI编译和应用程序运行都很好。但是,当使用ng test运行单元测试时,Karma或TypeScript编译器告诉我'String'类型不存在属性'padStart'

27 03 2019 10:40:57.424:INFO [karma-server]: Karma v4.0.1 server started at http://0.0.0.0:9876/
27 03 2019 10:40:57.424:INFO [launcher]: Launching browsers Chrome with concurrency unlimited
27 03 2019 10:40:57.429:INFO [launcher]: Starting browser Chrome
ERROR in node_modules/@azure/storage-blob/lib/utils/utils.common.ts(300,24): error TS2339: Property 'padStart' does not exist on type 'String'.
node_modules/@azure/storage-blob/lib/utils/utils.common.ts(301,26): error TS2339: Property 'padStart' does not exist on type 'string'.

当按照错误消息中的指示检查有问题的代码时:

export function padStart(
  currentString: string,
  targetLength: number,
  padString: string = " "
): string {
  if (String.prototype.padStart) {
    return currentString.padStart(targetLength, padString);
  }
...

我发现最后两行代码对我来说看起来很好,因为我知道padStart是在es2017中定义的,因此lib的程序员已经编写了这些代码。如果在tsconfig.json中我有lib = es2017和target = es2015,那么ng test的编译就可以了。

我想找出问题的原因,可疑的是:Type Script编译器,Karma,Angular编译器或有问题的代码。你觉得哪一个?

1 个答案:

答案 0 :(得分:0)

  

如果在tsconfig.json中我有lib = es2017和target = es2015,那么ng test的编译就可以了

这是正确的解决方法。 padStart仅与ES2017一起提供:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

enter image description here