【问题标题】:Method in Typescript does not compile because of Index Error由于索引错误,Typescript 中的方法无法编译
【发布时间】:2021-10-01 22:22:45
【问题描述】:

假设我想在 Typescript 中定义这个方法:

setResult(guId: string,fieldname: string, data:Array<UsedTsoClusterKey>) {
  let octdctruns: OctDctRun[] = [...this.octDctRuns];
  const index = octdctruns.findIndex((o) => o.guid === guId);
  octdctruns[index][fieldname] = data;
  this.octDctRuns = octdctruns;
}

UsedTsoClusterKey 和 OctDctRun 如下所示:

export interface UsedTsoClusterKey {
  runGUID: string;
  tsoClusterKeyID: string;
  tsoClusterKeyVersion: string;
  validFrom: DateString;
  validUntil: DateString;
}

export interface OctDctRun {
  guid: string;
  moduleType: string;
  runTime: DateString;
  calcIntervalFrom: DateString;
  calcIntervalUntil: DateString;
  triggerType: string;
  triggerID: string;
  usedTSOClusterKeys: UsedTsoClusterKey[];
}

但是我得到了一行错误 octdctruns[index][fieldname] = data:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'OctDctRun'.
  No index signature with a parameter of type 'string' was found on type 'OctDctRun'

我不明白这里的问题。请帮忙!

【问题讨论】:

  • 你不能使用string作为OctDctRun的键,太宽泛了。反正只有usedTSOClusterKeys这个字段可以赋值给UsedTsoClusterKey[],那为什么是参数呢?

标签: javascript typescript vue.js vuetify.js


【解决方案1】:

Typescript 不知道fieldNameOctDctRun 的属性,而且它不知道data 可以分配给您使用fieldName 寻址的属性。提供的另一个答案确实为此提供了解决方案,尽管有点特定于您的用例。但是,有一种更动态的方法可以做到这一点,不需要对 data 的类型进行硬编码:

class Test {
    setResult<FieldName extends keyof OctDctRun>(guId: string, fieldName: FieldName, data: OctDctRun[FieldName]) {
        let octdctruns = [...this.octDctRuns];
        const index = octdctruns.findIndex((o) => o.guid === guId);
        octdctruns[index][fieldName] = data;
        this.octDctRuns = octdctruns;
    }
}

如果您使用必须是 OctDctRun 的键的通用 FieldName,然后说参数 fieldName 必须是该类型,然后说 data 必须是以下值可分配给 fieldName,您可以在 100% 的时间内获得 100% 的类型安全性。

这里是游乐场Playground

【讨论】:

    【解决方案2】:

    fieldname: keyof OctDctRun - 这将解决您当前的问题,但这是另一个问题:dataUsedTsoClusterKey 实体的数组,因此它只能根据您的类型定义分配给 usedTSOClusterKeys。所以正确的类型定义是这样的:keyof Pick&lt;OctDctRun, 'usedTSOClusterKeys'&gt;,但我不确定它是否涵盖你的情况¯_(ツ)_/¯

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-11
      • 1970-01-01
      • 2021-07-06
      相关资源
      最近更新 更多