how to get Type from object value

Viewed 87
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?

2 Answers
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));

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

Related