我正在尝试转换包含时间序列参数的json JsonData
:
[
[ timestamp1, [ [paramset1, ...], [paramset2, ...], ...] ],
[ timestamp2, [ [paramset1, ...], [paramset2, ...], ...] ],
...
]
进入结构ParamPoint
export class ParamPoint{
constructor(
public tstamp: number,
public paramSets: number[][]
){}
}
带有如下代码:
let res = JsonData.map<ParamPoint>((p) => new ParamPoint(p[0], p[1]));
这会导致错误:
error TS2345: Argument of type 'number | number[][]' is not assignable to parameter of type 'number'.
Type 'number[][]' is not assignable to type 'number'.
我想知道错误的含义是什么以及应该如何避免。
答案 0 :(得分:1)
您需要为jsonData
定义类型,例如:
const jsonData: [number, number[][]][] = [
[1, [[1, 3], [2, 9]]],
[3, [[1, 7, 3], [2, 9]]],
]
其他打字稿将假定jsonData
中的所有内容都为number | number[][]
类型,而不是[number, number[][]]
您也可以尝试像这样投射它们
jsonData.map<ParamPoint>((p: [number, number[][]]) => new ParamPoint(p[0], p[1]))
甚至更好
jsonData.map<ParamPoint>(([a, b]: [number, number[][]]) => new ParamPoint(a, b))
另外,请不要从大写字母中调用变量,因为这会混淆类an类型的备用大写字母。
答案 1 :(得分:1)
代替:
let res = JsonData.map<ParamPoint>((p) => new ParamPoint(p[0], p[1]));
你能做
let res = JsonData.map((p:any) => new ParamPoint(p[0], p[1]));
相反?