Skip to content
The Chat Archive
gpt-3.5-turbo-0613· OpenAI WildChat-4.8M (AI2)

in a TypeScript conditional type, how can I get the type of the value that is being…

  1. User

    in a TypeScript conditional type, how can I get the type of the value that is being assigned

  2. Assistant

    In TypeScript, you can use the typeof operator in conditional types to get the type of the value that is being assigned. Here's an example:

    type ValueOrType<T> = T extends infer V ? V : never;
    
    // Example usage
    type TypeOfValue = ValueOrType<true>; // typeof true is "boolean"
    type TypeOfAssignedValue = ValueOrType<"Hello">; // typeof "Hello" is "string"
    

    In this example, ValueOrType is a conditional type that takes a generic type T. The conditional type T extends infer V ? V : never checks if the type parameter T can be inferred as V. If it can, V is returned as the resulting type. Otherwise, never is returned.

    By passing a value to ValueOrType, TypeScript will infer the type of that value using the typeof operator.

    Note that the typeof operator only works with literal values like true, "Hello", or 42. It doesn't work with expressions or variables.