是一组有序的成员类型构成,表示一个值的类型可以为若干种类型之一。
如果一个值是联合类型,我们只能访问此联合类型的所有类型里共有的成员。

联合类型字面量

  1. type StringOrNumber = string number

联合类型的类型成员

像接口类型一样,联合类型作为一个整体也可以有类型成员,只不过联合类型的类型成员是由其成员类型决定的

属性签名

Circle类型与Rectangle类型均包含名为area的属性签名类型成员,所以联合类型Shape也包含名为area的属性签名类型成员。因此,允许访问Shape类型上的area属性。
因为radius、width和height类型成员不是 Circle类型和Rectangle类型的共同类型成员,因此它们不是Shape联合类型的类型成员

  1. interface Circle {
  2. area:number;
  3. radius:number;
  4. }
  5. interface Rectangle {
  6. area:number;
  7. width:number;
  8. height:number
  9. }
  10. type Shape = Circle | Rectangle;

对于联合类型的属性签名,其类型为所有成员类型中该属性类型的联合类型

  1. interface Circle {
  2. area:number;
  3. }
  4. interface Rectangle {
  5. area:bigint;
  6. }
  7. type Shape = Circle | Rectangle;
  8. declare const s : Shape;
  9. s.area // bigint | number

如果联合类型的属性签名在某个成员中是可选属性签名,那么该属性签名在联合类型中也是可选属性签名

  1. interface Circle {
  2. area?:number;
  3. }
  4. interface Rectangle {
  5. area:bigint;
  6. }
  7. type Shape = Circle | Rectangle;
  8. declare const s : Shape;
  9. s.area // bigint | number | undefined

索引签名

索引签名包含两种,即字符串索引签名和数值索引签名。在联合类型中,这两种索引签名具有相似的行为
如果联合类型中每个成员都包含字符串索引签名,那么该联合类型也拥有了字符串索引签名,字符串索引签名中的索引值类型为每个成员类型中索引值类型的联合类型;否则,该联合类型没有字符串索引签名。例如,下例中的联合类型T相当于接口类型T0T1

  1. interface T0 {
  2. [propName:string]:number;
  3. }
  4. interface T1 {
  5. [propName:string]:bigint;
  6. }
  7. type T = T0 | T1;
  8. interface T0T1 {
  9. [propName:string]:bigint | number;
  10. }

调用签名与构造签名

如果联合类型中每个成员类型都包含相同参数列表的调用签名,那么联合类型也拥有了该调用签名,其返回值类型为每个成员类型中调用签名返回值类型的联合类型;否则,该联合类型没有调用签名。例如,下例中的联合类型T相当于接口类型T0T1:构造函数同理

  1. interface T0 {
  2. (name:string):number;
  3. }
  4. interface T1 {
  5. (name:string):bigint;
  6. }
  7. type T = T0 | T1;
  8. interface T0T1 {
  9. (name:string):bigint | number;
  10. }