Home > front end >  Conditional type is inferred differently with generic type
Conditional type is inferred differently with generic type

Time:11-02

Typescript infers the conditional type (with disabled distribution) differently when a generic type is passed.

type Box<T> = { a: T };

// Conditional type with disabled distribution using tuple.
type CondType<T> = [T] extends [string | number]
    ? Box<T> : false;

class Test<T extends string | number> {
    public constructor(private value: T) {}

    // CondType<T> is not inferred as Box<string | number>
    public one(param: CondType<T>): void {
        param; // type is false | Box<T>
    }

    // This works as expected
    public two(param: CondType<string | number>): void {
        param; // type is Box<string | number>
    }
}

Why is this? and is there a way around it?

CodePudding user response:

This is currently a missing feature in TypeScript. See microsoft/TypeScript#23132 for the relevant feature request. Its status is "awaiting more feedback" so it might be a good idea to go there, give it a

  • Related