【问题标题】:element implicitly has an 'any' type because type '{0}' has no index signature元素隐式具有“任何”类型,因为类型“{0}”没有索引签名
【发布时间】:2018-09-06 14:24:52
【问题描述】:

我想用给定的对象设置CanvasRenderingContext2D 上下文属性。但它总是抛出:

元素隐式具有“any”类型,因为类型“{0}”没有索引签名

我该如何解决这个问题?

interface Attr {
  fillStyle: string | CanvasGradient | CanvasPattern;
  font: string;
  globalAlpha: number;
  lineCap: string;
  lineWidth: number;
  lineJoin: string;
  miterLimit: number;
  shadowBlur: number;
  shadowColor: string;
  strokeStyle: string;
  textAlign: string;
  textBaseline: string;
  lineDash: string;
}

const element: HTMLCanvasElement = <HTMLCanvasElement>document.querySelector('#c');
const ctx: CanvasRenderingContext2D = element.getContext('2d');

let attr:Partial<Attr> = {
  fillStyle: 'red',
  globalAlpha: 0.8
}

function setAttrs(target: CanvasRenderingContext2D, attr: Partial<Attr>) {
  for (let p in attr) {
    target[p] = attr[p];
  }
}

VS 截图

【问题讨论】:

  • 这是因为CanvasRenderingContext2D 没有像[key:string]: string | number 这样的任何索引签名与之关联。并且您正在尝试通过 any 类型的索引键访问属性。你需要像这个问题stackoverflow.com/questions/42193262/…那样添加索引定义

标签: javascript typescript


【解决方案1】:

对于 Typescript,您无法通过索引访问 CanvasRenderingContext2D 的属性。您的对象Attr 也不能通过索引访问,所以实际上您有两个错误:target[p] 无效,attr[p] 也无效。当我说无效时,是因为调用 target[p]attr[p] 返回了一个隐式类型为 any 的变量,这是无效的,因为您在 tsconfig.json 中将标志 noImplicitAny 设置为 true

您可以通过添加索引签名[key:string]: any; 来修复您的界面,但您无法修复CanvasRenderingContext2D

第一个解决方案

通过将noImplicitAny 设置为false 来停用编译器规则。在tsconfig.json

{
  "compilerOptions": {
    "noImplicitAny": false
  }
}

第二种解决方案

将标志 suppressImplicitAnyIndexErrors 设置为 true。在tsconfig.json:

{
  "compilerOptions": {
    "noImplicitAny": true,
    "suppressImplicitAnyIndexErrors": true
  }
}

第三种解决方案

明确设置所有内容。我首选的解决方案,因为它保留了类型:

function setAttrs(target: CanvasRenderingContext2D, attr: Partial<Attr>) {
    target.fillStyle = attr.fillStyle;
    target.font = attr.font;
    target.globalAlpha = attr.globalAlpha;
    ...
}

这样你可以获得完整的类型覆盖,这样更好!

参考资料:

【讨论】:

    猜你喜欢
    • 2018-04-09
    • 2019-05-12
    • 1970-01-01
    • 2017-06-30
    • 2021-08-24
    • 2019-04-01
    • 2019-01-06
    • 2019-10-03
    • 1970-01-01
    相关资源
    最近更新 更多