尝试一个React项目的TypeScript,我被这个错误困住了:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ train_1: boolean; train_2: boolean; train_3: boolean; train_4: boolean; }'.
  No index signature with a parameter of type 'string' was found on type '{ train_1: boolean; train_2: boolean; train_3: boolean; train_4: boolean; }'

当我试图在我的组件中过滤数组时出现

.filter(({ name }) => plotOptions[name]);

到目前为止,我查看了文章“在TypeScript中索引对象”(https://dev.to/kingdaro/indexing-objects-in-typescript-1cgi),因为它有类似的错误,但我尝试将索引签名添加到类型plotTypes,我仍然得到相同的错误。

我的组件代码:

import React, { Component } from "react";
import createPlotlyComponent from "react-plotly.js/factory";
import Plotly from "plotly.js-basic-dist";
const Plot = createPlotlyComponent(Plotly);

interface IProps {
  data: any;
}

interface IState {
  [key: string]: plotTypes;
  plotOptions: plotTypes;
}

type plotTypes = {
  [key: string]: boolean;
  train_1: boolean;
  train_2: boolean;
  train_3: boolean;
  train_4: boolean;
};

interface trainInfo {
  name: string;
  x: Array<number>;
  y: Array<number>;
  type: string;
  mode: string;
}

class FiltrationPlots extends Component<IProps, IState> {
  readonly state = {
    plotOptions: {
      train_1: true,
      train_2: true,
      train_3: true,
      train_4: true
    }
  };
  render() {
    const { data } = this.props;
    const { plotOptions } = this.state;

    if (data.filtrationData) {
      const plotData: Array<trainInfo> = [
        {
          name: "train_1",
          x: data.filtrationData.map((i: any) => i["1-CumVol"]),
          y: data.filtrationData.map((i: any) => i["1-PressureA"]),
          type: "scatter",
          mode: "lines"
        },
        {
          name: "train_2",
          x: data.filtrationData.map((i: any) => i["2-CumVol"]),
          y: data.filtrationData.map((i: any) => i["2-PressureA"]),
          type: "scatter",
          mode: "lines"
        },
        {
          name: "train_3",
          x: data.filtrationData.map((i: any) => i["3-CumVol"]),
          y: data.filtrationData.map((i: any) => i["3-PressureA"]),
          type: "scatter",
          mode: "lines"
        },
        {
          name: "train_4",
          x: data.filtrationData.map((i: any) => i["4-CumVol"]),
          y: data.filtrationData.map((i: any) => i["4-PressureA"]),
          type: "scatter",
          mode: "lines"
        }
      ].filter(({ name }) => plotOptions[name]);
      return (
        <Plot
          data={plotData}
          layout={{ width: 1000, height: 1000, title: "A Fancy Plot" }}
        />
      );
    } else {
      return <h1>No Data Loaded</h1>;
    }
  }
}

export default FiltrationPlots;


当前回答

public getUserName():字符串{

const accessToken = this.getAccessToken();
const claims:any = this.getUserClaims();
console.log('access token ',accessToken);
this.getUserInfo();
return claims['sub'].split('@')[0];

}

//给变量任何类型

其他回答

输出打字错误

    const formData = new FormData();
    Object.keys(newCategory).forEach((k,i)=>{  
        var d =Object.values(newCategory)[i];
        formData.append(k,d) 
    })

我对Alex McKay的函数/用法做了一些小改动,我认为这样可以让它更容易理解为什么它可以工作,同时也遵循了定义前不使用的规则。

首先,定义这个函数来使用:

const getKeyValue = function<T extends object, U extends keyof T> (obj: T, key: U) { return obj[key] }

在我写它的方式中,函数的泛型首先列出对象,然后是对象上的属性(这些可以以任何顺序出现,但如果你在T扩展对象之前指定U扩展T的key,你就打破了定义前不使用的规则,而且对象在前,属性在后也是有意义的。最后,我使用了更常用的函数语法,而不是箭头操作符(=>)。

不管怎样,通过这些修改,你可以像这样使用它:

interface User {
  name: string;
  age: number;
}

const user: User = {
  name: "John Smith",
  age: 20
};

getKeyValue(user, "name")

同样,我觉得这样更有可读性。

它为我工作的keyof和作为操作符:

const keys: [keyof ITrainInfo] = Object.keys(this.trainInfo) as [
    keyof ITrainInfo,
]
keys.forEach((property) => {
    // console.log(tmpUser[property])
    if (this.trainInfo === undefined) return
    if (this.trainInfo[property] !== undefined) {
        // your code here
        /*const trainsToSet = trains.find((field) => field.name === property)
        if (trainsToSet != undefined)
            trainsToSet.value = this.trainInfo[property]?.toString()
        */
    }
})

TypeScript需要确保这些值存在于trainInfo中,否则它将全部读取为字符串

而不是这样做

interface trainInfo {
  name: string;
  x: Array<number>;
  y: Array<number>;
  type: string;
  mode: string;
}

这样做

interface trainInfo {
  name: "train_1" | "train_2" | "train_3"| "train_4";
  x: Array<number>;
  y: Array<number>;
  type: string;
  mode: string;
}

当使用Object时。按键,以下作品:

Object.keys(this)
    .forEach(key => {
      console.log(this[key as keyof MyClass]);
    });