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

188
Visualizações
how to get Type from object value
const arr=[{type:'a'},{type:'b'}]

type TypeFromVal<T>=T extends {type:infer R}[]?R:any

function GetType<T extends {type:string}[]>(arr:T,type:TypeFromVal<T>){
 return arr.find(item=>item.type===type).type
}

GetType(arr,0)

the auto infer is string or number ,i want to get type which is 'a'|0 i want to Typescript know function param type which infer from arr. In other words ,how to get type from infer?

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

0

const arr = [{type: 'a'}, {type: 'b'}];

type TypeFromVal = {
  type: string | number
}

function GetType(arr: Array<TypeFromVal>, type: number | string) {
  return arr.find(item => item.type === type)?.type
}

console.log(GetType(arr, 0));
about 4 years ago · Juan Pablo Isaza Relatório

0

In order to infer all types, you either should use as const for arr or pass it as a literal type to function instead passing reference.

type FindIndex<
  T extends Array<{ type: string }>,
  ExpectedType extends T[number]['type'],

  > = {
    [Prop in keyof T]:
    (T[Prop] extends { type: infer Type }
      ? (Type extends ExpectedType
        ? Prop
        : never
      )
      : never
    )
  }[number];
{
  // 0
  type Test = FindIndex<[{ type: 'a' }, { type: 'b' }], 'a'>
}

function GetType<
  Type extends string,
  Elem extends { type: Type },
  Arr extends Elem[],
  ExpectedType extends Arr[number]['type'],
  >(arr: [...Arr], type: ExpectedType): FindIndex<Arr, ExpectedType>
function GetType<
  Arr extends { type: string }[],
  ExpectedType extends Arr[number]['type'],
  >(arr: [...Arr], type: ExpectedType) {
  return arr.find((item) => item.type === type)
}

const result = GetType([{ type: 'a' }, { type: 'b' }], 'a') // 0

Explanation

FindIndex - iterates through literaly infered tuple/array and checks whether type property extends ExpectedType. If yes - return Prop, in our case this is an index. Otherwise - never. So, without [number] at the end, you will end up with [0, never]. Indexing it by [number] returns 0 | never, which is basically equals to 0.

I have overloaded GetType in order to apply out FindIndex.

Also, as you might have noticed, in order to infer literal type, you should infer every prop of element. You should go from the bottom to the top.

First generic Type infers type property. Then, Elem infers each element of the array. And finally Arr, thanks to variadic tuple types is fully infered.

You can find more information about tuple manipulations in my blog here and about type inference here

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