Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

193
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda