Union types and Intersection types

前端 未结 4 2156
天命终不由人
天命终不由人 2020-12-13 02:39

What are the various use cases for union types and intersection types? There has been lately a lot of buzz about these type system features, yet somehow I have never felt ne

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-13 03:20

    Union types are useful for typing dynamic languages or otherwise allowing more flexibility in the types passed around than most static languages allow. For example, consider this:

    var a;
    if (condition) {
      a = "string";
    } else {
      a = 123;
    }
    

    If you have union types, it's easy to type a as int | string.

    One use for intersection types is to describe an object that implements multiple interfaces. For example, C# allows multiple interface constraints on generics:

    interface IFoo {
      void Foo();
    }
    
    interface IBar {
      void Bar();
    }
    
    void Method(T arg) where T : IFoo, IBar {
      arg.Foo();
      arg.Bar();
    }
    

    Here, arg's type is the intersection of IFoo and IBar. Using that, the type-checker knows both Foo() and Bar() are valid methods on it.

提交回复
热议问题