2 years ago

#47813

test-img

tiancheng

When does typescript infer result of 'extends' as union of results?

I try to write a generic utility type to check if a type is unioned with a given type.

However, it doesn't work well.

type IsUnionWith<T, U> = U extends T
  ? T extends U
    ? false
    : true
  : false;

type OnlyString = IsUnionWith<string, undefined>; // false, as expected
type UnionString = IsUnionWith<string | undefined, undefined>; // boolean, I expect it to be 'true'
type OnlyUndefined = IsUnionWith<undefined, undefined>; // false, as expected

I wonder why UnionString is boolean instead of true.

Another example works just as expected.

type IsTypeEqual<T, P> = T extends P
  ? P extends T
    ? true
    : false
  : false;

typescript

generics

union

extends

0 Answers

Your Answer

Accepted video resources