Search code examples
typescripttypesconditional-types

Conditional type check for undefined


For the code

type stringUndefined = "string" | undefined;

type What<T> = T extends undefined ? "true" : "false";

const no : What<stringUndefined> = "";

no becomes "true" | "false" instead of what I would expect, "true"

TS-Playground

Code

Edit:

strict null checks are enabled


Solution

  • "string" | undefined doesn't extend undefined, because it can be "string".

    But undefined extends "string" | undefined, because the members of a union extend (refine) the union. So:

    type StringLiteralOrUndefined = "string" | undefined;
    
    type What<T> = undefined extends T ? true : false;
    
    type X = What<StringLiteralOrUndefined>;
    //   ^? type X = true
    
    type UnrelatedType = string | number;
    
    type Y = What<UnrelatedType>;
    //   ^? type Y = false
    

    Playground