DEV Community

Discussion on: How to make Generic Functions that change return value type according to the parameter values type in TypeScript?

Collapse
 
captainyossarian profile image
yossarian • Edited

Small improvement:

type Json = number | boolean | string | { [prop: string]: Json } | Array<Json>;

const getFirstElement = <Elem extends Json, Tuple extends Elem[]>(
  arr: [...Tuple]
): Tuple[0] => arr[0];

const value1 = getFirstElement([1, 2, 3, 4]); // 1

const value2 = getFirstElement(["hello", "hai", "hey"]); // "hello"
Enter fullscreen mode Exit fullscreen mode

As you might have noticed, TS is able to infer literal type with help of Variadic tuple types.
You can find more examples in my blog here and here