0

I've got the following interface. Variable access like metrics[ key[1] ] is not allowed because not string indexable. Is there another way to access a single element dynamically, like metrics.{key[1]}? Or a way to make it string indexable while keeping it's structure?

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 }
  };

1 Answer 1

1

If you're starting out with a string type, you can narrow it down to one of the Metrics keys allowed and then use bracket notation:

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]);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Ok I see. But then I would have to do that for the .audio .video .min .avg .max keys as well. That is a lot of type checking while the keys already come from a list of valid keys. No other way than using // @ts-ignore then?
If you're sure that the accesses that will be attempted are all type-correct without carrying out the checks, you could use as to tell TS that there's no need to check them, eg metrics[str as keyof Metrics] - but ideally you'd have the strings typed as proper properties in the first place, avoiding the need for this sort of thing.
I see. Will have a look at the key typing then. Thank U!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.