0

I'll start with example code.

toggle<K extends keyof T, V = T[K] extends any[] ? T[K] : never>(key: K, value: V): ...

I call this function on array-like properties. Since V or T[K] is array-like type (eg. string[]), I want it to be just string. Note that it can be any array type.

Is this possible to get just string type out of V?

interface ITest {
  prop1: number;
  prop2: number[];
}

T is for example ITest When key(K) is prop2, V should be number, else if key is prop1, V should be never

Behaviour:

toggle("prop2", "string") type error

toggle("prop2", [1, 2]) type error

toggle("prop2", 1) valid

jank
  • 840
  • 4
  • 7

1 Answers1

1

The simplest way is to use a lookup type with number as the property type:

type ArrayComponent<A extends any[]> = A[number];

You can also do it using a conditional type with an infer declaration:

type ArrayComponent<A extends any[]> = A extends (infer U)[] ? U : never;

Either way, ArrayComponent<V> will be the component type when V is an array type.

kaya3
  • 47,440
  • 4
  • 68
  • 97