Twiggeh
Twiggeh

Reputation: 1160

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

Upvotes: 0

Views: 112

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074038

"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

Upvotes: 3

Related Questions