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

162
Visualizações
Typescript: How to preserve length information when using .map

My current "working" approach is this:

const generateMainOrientations = <T extends readonly string[]>(
  mainOrientationsNames: T
): { [Index in keyof T]: Orientation } => {
  const temp: Orientation[] = mainOrientationsNames.map(
    mainOrientationName => ({
      name: mainOrientationName,
      getYear(date) {
        return date.getFullYear()
      },
      getRecordContent: getMainOrientationRecordContent
    })
  )

  return temp as unknown as { [Index in keyof T]: Orientation }
}

const mainOrientations = generateMainOrientations([
  "One",
  "Two",
  "Three"
] as const)

However, I have to use as unknown as { [Index in keyof T]: Orientation }, which is not ideal, otherwise (even removing the type assertion from the temp variable) it will throw

Type '{ name: string; getYear(date: any): any; getRecordContent: (values: number[]) => string[]; }[]' is not assignable to type '{ [Index in keyof T]: Orientation; }'.ts(2322)

Still, { name: string; getYear(date: any): any; getRecordContent: (values: number[]) => string[]; } is the definition of Orientation

This shows that any length information is lost after map is used.

Is there a more organic way to achieve this, preferably without having to use type assertions at all, or at least without having to use as unknown. The objective would be to make mainOrientations a tuple of Orientation of the same length as the argument passed to generateMainOrientations, so [Orientation, Orientation, Orientation] in this case, (not Orientation[]).

Playground

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

0

You need to overload your function:

interface Orientation {
  name: string,
  getYear(date: Date): number,
  getRecordContent(values: number[]): string[]
}

declare function getMainOrientationRecordContent(values: number[]): string[]

function generateMainOrientations<T extends string, Tuple extends T[]>(
  mainOrientationsNames: [...Tuple]
): { [Index in keyof Tuple]: Orientation }
function generateMainOrientations(
  mainOrientationsNames: string[]
) {
  return mainOrientationsNames.map(
    mainOrientationName => ({
      name: mainOrientationName,
      getYear: (date: Date) => date.getFullYear(),
      getRecordContent: getMainOrientationRecordContent
    })
  )
}

// [Orientation, Orientation, Orientation]
const mainOrientations = generateMainOrientations([
  "One",
  "Two",
  "Three"
])

Playground

Please keep in mind, that once you used Array.prototype.map , typescript don't preserve the length of the result. Here you can find why.

hence, you have only two options: overloading and type assertion.

You can do even better if you make name property parametrized :

interface Orientation<Name extends string> {
  name: Name,
  getYear(date: Date): number,
  getRecordContent(values: number[]): string[]
}

declare function getMainOrientationRecordContent(values: number[]): string[]

function generateMainOrientations<T extends string, Tuple extends T[]>(
  mainOrientationsNames: [...Tuple]
): { [Index in keyof Tuple]: Orientation<Tuple[Index] & string> }
function generateMainOrientations(
  mainOrientationsNames: string[]
) {
  return mainOrientationsNames.map<Orientation<string>>(
    name => ({
      name,
      getYear: (date) => date.getFullYear(),
      getRecordContent: getMainOrientationRecordContent
    })
  )
}

// [Orientation<"One">, Orientation<"Two">, Orientation<"Three">]
const mainOrientations = generateMainOrientations([
  "One",
  "Two",
  "Three"
])
about 4 years ago · Juan Pablo Isaza Relatório

0

You can use temp as any

const generateMainOrientations = <T extends readonly string[]>(
  mainOrientationsNames: T
): { [Index in keyof T]: Orientation } => {
  const temp = mainOrientationsNames.map((mainOrientationName) => ({
    name: mainOrientationName,
    getYear(date: Date) {
      return date.getFullYear();
    },
    getRecordContent: getMainOrientationRecordContent
  }));

  return temp as any;
};
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