Typescript 声明多维对象
我有以下对象结构 变量名称:metrics 结构:指标[期间][查看] 其中period为string,view为string,metrics[period][view]的类型为Item[] 我试着宣布Typescript 声明多维对象,typescript,Typescript,我有以下对象结构 变量名称:metrics 结构:指标[期间][查看] 其中period为string,view为string,metrics[period][view]的类型为Item[] 我试着宣布 metrics: { [period:string] : { [view:string] : Item[][] } } = []; 但我得到了以下错误: Type 'never[]' is not assignable to type '{ [period: str
metrics: {
[period:string] : {
[view:string] : Item[][]
}
} = [];
但我得到了以下错误:
Type 'never[]' is not assignable to type '{ [period: string]: { [view: string]: Item[][]; }; }'.
Index signature is missing in type 'never[]'.ts(2322)
如何正确声明对象类型?索引签名是TypeScript接口中必须为string或number类型的参数。我们可以用它来表示动态对象的属性。例如,我们可以像在以下代码中一样使用它:
interface IMetric<T> {
[peroid: string]: {
[view: string]: T;
};
}
const metrics: IMetric<Item[][]> = {
period: {
view: [[], []]
}
};
所以
console.log(metrics.period.view)
或console.log(metrics['period']['view'])
您试图将类型为{[period:string]:{[view:string]:Item[]];};}的对象声明为空数组