繁体   English   中英

在 Typescript 接口中访问索引

[英]Accessing index in Typescript Interface

我使用索引类型在 Typescript 中创建了一个字典,我正试图在我的代码中的某个地方使用它。 但无法弄清楚如何访问索引。 我有两个接口:

export interface OrderForm {
 model_id?: number;
 model_color_id?: number;
 model_product_id?: number;
 total_lld: ComputedTotalLLDOptions;
 product_parts_id?: string;
}

export interface ComputedTotalLLDOptions {
  [index: number]: {
    contribution: number;
    duration: number;
    rent: number;
  };
}

你有一些我如何使用它的例子吗?

接口定义了代码中“事物”的形状; 它们提供 static 类型并且没有运行时功能。 您可以使用它们来指定变量/参数/属性的预期类型。 您的ComputedTotalLLDOptions示例:

const foo: ComputedTotalLLDOptions = {
    0: {
        contribution: 1,
        duration: 2,
        rent: 3
    }
}

const bar: number = foo[0].contribution

看到这个游乐场

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM