【问题标题】:Typescript: How to dynamic access interface property when string index is not allowed?Typescript:不允许字符串索引时如何动态访问接口属性?
【发布时间】:2021-05-01 19:36:45
【问题描述】:

我有以下界面。不允许像 metrics[ key[1] ] 这样的变量访问,因为字符串不可索引。是否有另一种方法可以动态访问单个元素,例如 metrics.{key[1]}?或者在保持其结构的同时使其字符串可索引的方法?

export interface Metrics {
  bufferLevel?: { audio: number, video: number };
  bitrateDownload?: { audio: number, video: number };
  qualityIndex?: { audio: number, video: number };
  qualityIndexPending?: { audio: number, video: number };
  qualityIndexMax?: { audio: number, video: number };
  droppedFrames?: { audio: number, video: number };
  latency?: {
    audio: { min: number, avg: number, max: number },
    video: { min: number, avg: number, max: number }
  };

【问题讨论】:

    标签: typescript strict


    【解决方案1】:

    如果您从字符串类型开始,可以将其缩小到允许的 Metrics 键之一,然后使用括号表示法:

    declare const metrics: Metrics;
    const isValidMetricsKey = (str: string): str is keyof Metrics => ['bufferLevel', 'bitrateDownload', 'qualityIndex', 'qualityIndexPending', 'qualityIndexMax', 'droppedFrames', 'latency'].includes(str);
    const str: string = 'foo';
    if (isValidMetricsKey(str)) {
       console.log(metrics[str]);
    }
    

    【讨论】:

    • 好的,我明白了。但是我也必须为 .audio .video .min .avg .max 键这样做。这是大量的类型检查,而密钥已经来自有效密钥列表。除了使用 // @ts-ignore 之外别无他法?
    • 如果您确定将尝试的访问都是类型正确的而不进行检查,您可以使用as 告诉 TS 不需要检查它们,例如 @ 987654324@ - 但理想情况下,您应该首先将字符串类型化为适当的属性,从而避免此类事情的需要。
    • 我明白了。那就看看键位吧。谢谢你!
    猜你喜欢
    • 2016-02-23
    • 1970-01-01
    • 2021-04-29
    • 2020-11-04
    • 1970-01-01
    • 2021-05-13
    • 2021-07-30
    • 2020-09-18
    相关资源
    最近更新 更多