Home > Net >  How to use string as key for array in TypeScript
How to use string as key for array in TypeScript

Time:09-25

I have a TypeScript problem:

let classStart: keyof typeof monday;
const now = new Date();
console.log(now.getHours());
for (let i = Object.keys(monday).length - 1; i > 0; i--) {
  let time: any = Object.keys(monday)[i].split(":");
  // eslint-disable-next-line eqeqeq
  if (time[0] == now.getHours()) {
    if (time[1] <= now.getMinutes()) {
      console.log(Object);
      classStart = Object.keys(monday)[i];
      console.log();
    } else {
      //classStart = Object.keys(monday)[i - 1];
      console.log(Object.keys(monday)[i - 1]);
    }

    // console.log(monday[classStart]);
  }
}

This is my code, I need to use the Object.keys(monday)[i] (which is a string) as a property for monday[].

If I use the let classStart: keyof typeof monday; I can assign e.x "7:25" to classStart but I can't assign it using a function like Object.keys(monday)[i];. Why?

The JSON where I get the data from looks like this:

    ...
    "7:25": ["B1", "B2", "B3","B4"],
    ...

It is a typescript problem. I'm quite sure.

CodePudding user response:

I think the main problem, that no one can guess what is the type of monday, (TypeScript too). So if you specify its type, the problem will become much more clearer

I suspect that

monday: {
   [HHMM:string]: string[]
}

So I slightly altered your code

const mondayInput = {
    "10:13": ["B1"],
    "7:25": ["B1", "B2", "B3","B4"]
};
const monday = mondayInput as Record<string,string[]>

//fixed date time for test proposes
let now = new Date("2013/01/01 10:10:00")
console.log(now, now.getHours(),  now.getMinutes());

function HHMMtoInt(x:string){const [HH, MM] = x.split(":"); return parseInt(HH) * 100   parseInt(MM)}
const times = Object.keys(monday).sort((a,b) => HHMMtoInt(a)-HHMMtoInt(b));

for (let i = 0;i < times.length; i  ) {
  const  timeHHMM = times[i]; 

  let time = timeHHMM.split(":").map(x => parseInt(x));

  let timeInterval: number | undefined;
  console.log("Compare", time[0], time[1], now.getHours(), now.getMinutes())
  if (time[0] == now.getHours()) {
    if (time[1] <= now.getMinutes()) {
        timeInterval = i;
    } else {
        timeInterval = i - 1; 
    }
  }
  
  if(timeInterval !== undefined && timeInterval >= 0 ){
      console.log("Time", times[timeInterval], "Classes", monday[times[timeInterval]] );
  }
}

Playground Link: Provided

  • Related