正在尝试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),因为它有一个类似的错误,但是我试图将索引签名添加到typeplotTypes
中,我仍然得到同样的错误。
我的组件代码:
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;
发生这种情况是因为您试图使用字符串name
访问plotOptions
属性。TypeScript理解name
可能具有任何值,而不仅仅是plotOptions
中的属性名称。所以TypeScript需要向plotOptions
添加索引签名,这样它就知道您可以在plotOptions
中使用任何属性名称。但是我建议更改name
的类型,所以它只能是plotOptions
属性之一。
interface trainInfo {
name: keyof typeof plotOptions;
x: Array<number>;
y: Array<number>;
type: string;
mode: string;
}
现在,您将只能使用plotOptions
中存在的属性名称。
您还必须稍微更改代码。
首先将数组分配给某个临时变量,以便TS知道数组类型:
const plotDataTemp: 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"
},
// ...
}
然后筛选:
const plotData = plotDataTemp.filter(({ name }) => plotOptions[name]);
如果您正在从API获取数据,并且在编译时无法键入检查道具,那么唯一的方法就是将索引签名添加到绘图选项中:
type tplotOptions = {
[key: string]: boolean
}
const plotOptions: tplotOptions = {
train_1: true,
train_2: true,
train_3: true,
train_4: true
}
使用对象时。按键
,以下功能:
Object.keys(this)
.forEach(key => {
console.log(this[key as keyof MyClass]);
});
// bad
const _getKeyValue = (key: string) => (obj: object) => obj[key];
// better
const _getKeyValue_ = (key: string) => (obj: Record<string, any>) => obj[key];
// best
const getKeyValue = <T extends object, U extends keyof T>(key: U) => (obj: T) =>
obj[key];
坏-错误的原因是对象
类型在默认情况下只是一个空对象。因此,不可能使用字符串
类型来索引{}
。
更好的是,错误消失的原因是因为现在我们告诉编译器obj
参数将是字符串/值(string/any
)对的集合。但是,我们使用的是any
类型,所以我们可以做得更好。
最佳-T
扩展空对象。U
扩展T
的键。因此U
将始终存在于T
上,因此它可以用作查找值。
下面是一个完整的例子:
我已经切换了泛型的顺序(U extends keyof T
现在位于T extends object
之前),以强调泛型的顺序并不重要,您应该选择一个对您的函数最有意义的顺序。
const getKeyValue = <U extends keyof T, T extends object>(key: U) => (obj: T) =>
obj[key];
interface User {
name: string;
age: number;
}
const user: User = {
name: "John Smith",
age: 20
};
const getUserName = getKeyValue<keyof User, User>("name")(user);
// => 'John Smith'
const getKeyValue = <T, K extends keyof T>(obj: T, key: K): T[K] => obj[key];