Home > OS >  Accessing object property in Typescript using variable
Accessing object property in Typescript using variable

Time:06-26

I have following model

interface Budget {
    budget_july?: number,
    budget_august?: number,
    budget_september?: number,
    budget_october?: number,
    budget_november?: number,
    budget_december?: number,
    budget_january?: number,
    budget_february?: number,
    budget_march?: number,
    budget_april?: number,
    budget_may?: number,
    budget_june?: number
}

I am trying to trying to access the property dynamically using a variable, like so:

const budgets: Budget[] = [];

var datestr = '2022-07-01';

const budget_month: keyof Budget = 'budget_'   new Date(datestr).toLocaleString('default', { month: 'long' }).toLowerCase();
budgets[0][budget_month] = 5000;

Here I get error : Type 'string' is not assignable to type 'keyof Budget'

Following works:

const budget_month = 'budget_july';  budgets[0][budget_month] = 5000;

I have worked out a workaround using switch/case but its ugly. Is it possible to make this work like I did here?

CodePudding user response:

Typescript can't track all that string transformation and know that it will be a keyof Budget at the end.

I think you may be better off with a type assertion that casts the string to a keyof Budget:

const budget_month =
  'budget_'  
  new Date(datestr)
    .toLocaleString('default', { month: 'long' })
    .toLowerCase() as keyof Budget;
  • Related