Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

223
Visualizações
How to use string as key for array in TypeScript

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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda