【问题标题】:Accessing objects field using string in Typescript在 Typescript 中使用字符串访问对象字段
【发布时间】:2021-09-01 01:12:01
【问题描述】:

我有一个由多个公共成员组成的课程。

为简单起见,我们假设:

class ComponentData {
  id: number;
  type: ComponentType;
  location: ComponentLocation;
  label: string;
  value: number;
}

我确实定义了一个类型:

type Layout = {[field in keyof ComponentData]?: InputSchema};

使用 Object.keys(layout) 我正在为不同的 ComponentTypes 显示不同的输入集。这很好用,但是稍后输入 onChange 我正在尝试修改源 ComponentData。

function onPropertyChange(newValue: unknown, fieldName: string) {
    selectedItem[fieldName] = newValue;
}

我收到了:

TS7053:元素隐式具有“任何”类型,因为“字符串”类型的表达式不能用于索引类型“组件数据”。在“ComponentData”类型上找不到带有“string”类型参数的索引签名。

我尝试遵循此处建议的解决方案: https://stackoverflow.com/a/66838662/8191341 如下:

function onPropertyChange(newValue: unknown, fieldName: string) {
    const key = fieldName as keyof ComponentData;
    selectedItem![key] = newValue;
}

但后来收到了:

TS2322:类型“InputValues”不可分配给类型“从不”。类型“未定义”不可分配给类型“从不”。

有什么想法吗? :)

PS。使用 //@ts-ignore 它按预期工作,但我对解决方案不满意。

【问题讨论】:

    标签: javascript string typescript types


    【解决方案1】:

    我用这个 tsconfig [1] 重现了错误,这段代码解决了这个问题:

    function onPropertyChange(newValue: unknown, fieldName: string) {
      Object.assign(selectedItem, { [fieldName]: newValue });
    }
    

    [1]

    {
      "compilerOptions": {
        "target": "es2019",
        "module": "commonjs",
        "allowJs": false,
        "outDir": "./dist",
        "strict": true,
        "lib": ["es2019","DOM"],
        "typeRoots": ["node_modules/@types"],
        "esModuleInterop": true,
        "sourceMap": true
      },
      "include": ["src/**/*.ts"],
      "exclude": ["node_modules", "src/**/*.spec.ts"]
    }
    

    【讨论】:

      猜你喜欢
      • 2020-08-13
      • 1970-01-01
      • 2011-02-12
      • 1970-01-01
      • 1970-01-01
      • 2021-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多