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

132
Visualizações
How to stored different typed functions underr the same object key?

I store values and individual typed functions in an array of objects. When looping the array all the types of all typed functions in the array are required for any value. How can I write it more specific?

ts playground

TS ERROR

Argument of type 'boolean | string[]' is not assignable to parameter of type 'string[] & boolean'.

Type 'false' is not assignable to type 'string[] & boolean'.

const arrayToString = (arg: string[]): string => arg.join(", ")
const booleanToString = (arg:boolean): string => (arg ? "yes" : "no")

const data = [{
  value: true,
  render: booleanToString
  },
  {
    value: ["a","b"],
    render: arrayToString
  }
]

data.map(item =>{
  item.render(item.value) // ts error
})
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

One way around this is by declaring the argument as an intersect type:

render(item.value as boolean & string[]) // no error

This tells the compiler to accept both types. It works much like polymorphic behavior because the type includes both possibilities.

about 4 years ago · Juan Pablo Isaza Relatório

0

This is a shortcoming of Typescript and a design limitation. It correctly types item.value as boolean | string[] and conversely it correctly types item.render as typeof arrayToString | typeof booleanToString. However, in order to ensure type-safety, Typescript doesn't know which function it is, so to guarantee it will not error on either, it intersects the parameters, hence boolean & string[]. The intersection of these two primitives is never. This is because Typescript types doesn't have iterable discrimination.

A possible workaround is to cast it as never

data.map(({value, render}) =>{
  render(value as never);
})

My recommendation (if you are setting data this way) is to create a type to ensure that render always accepts the associated value as parameters

type ObjectWithRender<T> = {
  value: T
  render: (arg: T) => string
}

const data: [
  ObjectWithRender<boolean>,
  ObjectWithRender<[string, string]>
] = [
  {
    value: true,
    render: booleanToString
  },
  {
    value: ["a","b"],
    render: arrayToString
  }
]

Or alternatively create a helper function to infer value and renderValue... But this carries some downsides, namely your functions will now have to accept readonly args. It'll also affect compilation-to-runtime with an effectively useless function.

function validateData<T extends ReadonlyArray<any>>(data: {
  [K in keyof T]: {
    value: T[K]
    render: (arg: T[K]) => string
  }
}
) {return data}

// Will throw an error if value isn't the render arg
const validatedData = validateData(
  [
    {
      value: true,
      render: booleanToString
    },
    {
      value: ['a', 'b'],
      render: arrayToString
    }
  ] as const
)

View on TS Playground

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