Use a string as an object’s property name in typescript

  Kiến thức lập trình

Given an object with a type like the one below:

type Variables = {
  _id: string;
  variable1: string;
  variable2: string | null;
  variable3: string | null;
  variable4: string | null;
  variable5: string | null;
}

Is it possible to access one of its properties using bracket notation and a string, without tricking Typescript’s type system? Currently I’m doing it (roughly) like this:

const level = 1;
const propertyName = `variable${level}` as unknown as keyof Variables;
const variableAtLevel = instance[propertyName];

Even though I have implemented safeguards so as to not try to access something that doesn’t exist, this looks hacky at best, and a potential failure point at worst. Is there a safer way to do it?

LEAVE A COMMENT