1

I was reading about TypeScript 2.8 - Conditional Types and I saw a lot of examples in the Typescript docs where they list the resolved? version of a type as comments next to it:

type TypeName<T> =
    T extends string ? "string" :
    T extends number ? "number" :
    T extends boolean ? "boolean" :
    T extends undefined ? "undefined" :
    T extends Function ? "function" :
    "object";

type T0 = TypeName<string>;  // "string"
type T1 = TypeName<"a">;  // "string"
type T2 = TypeName<true>;  // "boolean"
type T3 = TypeName<() => void>;  // "function"
type T4 = TypeName<string[]>;  // "object"

For example TypeName<true> is actually boolean. This becomes even more useful with even more complex scenarios, where you can see what type you've actually constructed:

type FunctionPropertyNames<T> = { [K in keyof T]: T[K] extends Function ? K : never }[keyof T];
type FunctionProperties<T> = Pick<T, FunctionPropertyNames<T>>;

type NonFunctionPropertyNames<T> = { [K in keyof T]: T[K] extends Function ? never : K }[keyof T];
type NonFunctionProperties<T> = Pick<T, NonFunctionPropertyNames<T>>;

interface Part {
    id: number;
    name: string;
    subparts: Part[];
    updatePart(newName: string): void;
}

type T40 = FunctionPropertyNames<Part>;  // "updatePart"
type T41 = NonFunctionPropertyNames<Part>;  // "id" | "name" | "subparts"
type T42 = FunctionProperties<Part>;  // { updatePart(newName: string): void }
type T43 = NonFunctionProperties<Part>;  // { id: number, name: string, subparts: Part[] }

That could certainly help me when confusion about types arise, so I was wondering if there is any way to have the compiler extract that same type information?

ᴘᴀɴᴀʏɪᴏᴛɪs
  • 7,169
  • 9
  • 50
  • 81

2 Answers2

1

Visual Studio code already provides this functionality if you hover over a conditional type. For your example this is what it looks like :

enter image description here

Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357
  • For larger types it has a lot of `...` in it, is there anyway to get the full type and to be able to copy paste it? I tried this but it doesnt work - https://stackoverflow.com/a/67235137/1828637 – Noitidart Jul 03 '22 at 14:58
0

This SO answer came one year later and I still find it useful:

// expands object types one level deep
export type DebugExpand<T> = T extends infer O
  ? { [K in keyof O]: O[K] }
  : never;

// expands object types recursively
export type DebugExpandRecursive<T> = T extends object
  ? T extends infer O
    ? { [K in keyof O]: DebugExpandRecursive<O[K]> }
    : never
  : T;

Credits to its author, I just renamed/formatted them.

superjos
  • 12,189
  • 6
  • 89
  • 134
  • is this not when you should dup-vote? – starball Jul 12 '23 at 17:58
  • I found another question on same topic which was more recent, and I voted for duplication. But this one is older is instead, plus it has an accepted answer. Did not seem like a duplicate to me. – superjos Jul 14 '23 at 08:11