是一组有序的成员类型构成,表示一个值的类型可以为若干种类型之一。
如果一个值是联合类型,我们只能访问此联合类型的所有类型里共有的成员。
联合类型字面量
type StringOrNumber = string | number
联合类型的类型成员
像接口类型一样,联合类型作为一个整体也可以有类型成员,只不过联合类型的类型成员是由其成员类型决定的
属性签名
Circle类型与Rectangle类型均包含名为area的属性签名类型成员,所以联合类型Shape也包含名为area的属性签名类型成员。因此,允许访问Shape类型上的area属性。
因为radius、width和height类型成员不是 Circle类型和Rectangle类型的共同类型成员,因此它们不是Shape联合类型的类型成员
interface Circle {area:number;radius:number;}interface Rectangle {area:number;width:number;height:number}type Shape = Circle | Rectangle;
对于联合类型的属性签名,其类型为所有成员类型中该属性类型的联合类型
interface Circle {area:number;}interface Rectangle {area:bigint;}type Shape = Circle | Rectangle;declare const s : Shape;s.area // bigint | number
如果联合类型的属性签名在某个成员中是可选属性签名,那么该属性签名在联合类型中也是可选属性签名
interface Circle {area?:number;}interface Rectangle {area:bigint;}type Shape = Circle | Rectangle;declare const s : Shape;s.area // bigint | number | undefined
索引签名
索引签名包含两种,即字符串索引签名和数值索引签名。在联合类型中,这两种索引签名具有相似的行为
如果联合类型中每个成员都包含字符串索引签名,那么该联合类型也拥有了字符串索引签名,字符串索引签名中的索引值类型为每个成员类型中索引值类型的联合类型;否则,该联合类型没有字符串索引签名。例如,下例中的联合类型T相当于接口类型T0T1
interface T0 {[propName:string]:number;}interface T1 {[propName:string]:bigint;}type T = T0 | T1;interface T0T1 {[propName:string]:bigint | number;}
调用签名与构造签名
如果联合类型中每个成员类型都包含相同参数列表的调用签名,那么联合类型也拥有了该调用签名,其返回值类型为每个成员类型中调用签名返回值类型的联合类型;否则,该联合类型没有调用签名。例如,下例中的联合类型T相当于接口类型T0T1:构造函数同理
interface T0 {(name:string):number;}interface T1 {(name:string):bigint;}type T = T0 | T1;interface T0T1 {(name:string):bigint | number;}
