微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Angular 12 - 不可分配给类型 '[number, number]

如何解决Angular 12 - 不可分配给类型 '[number, number]

我正在 Angular 12 中试用 ngx-charts 库,但我一直遇到这个问题:

类型 'any[]' 不能分配给类型 '[number,number]'。

目标需要 2 个元素,但源可能更少。

我不知道错误是什么意思。

代码如下:

HTML:

<ngx-charts-linear-gauge 
  [view]="view" 
  [scheme]="colorScheme" 
  [value]="value" 
  [prevIoUsValue]="prevIoUsValue" 
  (select)="onSelect($event)" 
  [units]="units"
>
</ngx-charts-linear-gauge>

ts:

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',templateUrl: './app.component.html',styleUrls: ['./app.component.scss']
})
export class AppComponent {

  single: any[];
  view: any[] = [400,400];
  colorScheme = {
    domain: ['#aae3f5']
  };
  value: number = 43;
  prevIoUsValue: number = 70;
  units: string = 'counts';

  onSelect(event) {
    console.log(event);
  }

}

关于错误意味着什么的任何想法,如何解决这个问题?

ts 配置代码是:

{
  "compileOnSave": false,"compilerOptions": {
    "baseUrl": "./","outDir": "./dist/out-tsc","forceConsistentCasingInFileNames": true,"strict": false,"noImplicitReturns": true,"noFallthroughCasesInSwitch": true,"sourceMap": true,"declaration": false,"downlevelIteration": true,"experimentalDecorators": true,"moduleResolution": "node","importHelpers": true,"target": "es2017","module": "ES2020","lib": [
      "es2018","dom"
    ]
  },"angularCompilerOptions": {
    "enableI18nLegacyMessageIdFormat": false,"strictInjectionParameters": true,"strictInputAccessModifiers": true,"strictTemplates": true
  }
}

解决方法

我想问题在于您的 view 属性类型。根据鳕鱼,它必须是 number[] 类型:doc-ref
注意:文档中的类型不够准确。 view 不是定义为数字数组 (number[]),而是定义为 2 个数字的元组 ([number,number]) - source-code ref

但是您将其定义为 any[]
根据您的打字稿编译器设置,您可能会收到错误或警告。

当您需要完全正确的类型时,请使用:

// use as const so that typescript will infer the type [number,number] instead of number[]
view = [400,400] as const;

显式类型为:

view: [number,number] = [400,400];

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。