1

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;
tiancheng
  • 11
  • 2
  • You are using [distributive conditional types](https://www.typescriptlang.org/docs/handbook/2/conditional-types.html#distributive-conditional-types) when you don't mean to. Change it to [this](https://tsplay.dev/wOzM6W) to fix it. – jcalz Jan 13 '22 at 17:04
  • @jcalz Thank you very much! This is what I need exactly. – tiancheng Jan 14 '22 at 06:52

0 Answers0