Skip to Content

类型别名(Type Alias)

typealias 给既有类型起新名字。

类型别名

别名是完全透明的:新名字就是原类型本身,赋值、运算、is 测试都与原类型互通。

typealias Meters = int; typealias StrList = list<string>; func main() -> int { val m: Meters = 5; print(m + 1, m is int); val plain: int = m; print(plain); val xs = new StrList(); xs.Add("甲"); print(xs[0], xs.Count); return 0; }
6 True 5 甲 1

数组别名同样成立:typealias Row = int[]; 之后 val r: Row = [1, 2, 3]; 合法,r is int[] 为 True。泛型别名带类型参数,实例化使用:

typealias Pair<T, U> = (T, U); func main() -> int { val p: Pair<int, string> = (7, "七"); print(p.Item0, p.Item1); return 0; }
7 七

别名环在编译期拒绝,报 MS3114:

error MS3114: Type alias cycle: A → A.

别名只起新名字,不创造新类型:Meters 与 int 在类型检查器里是同一个类型,转换、判等、重载分派上没有任何差别。想要「换了名字就互不相赋」的纪律,别名给不了,那是宿主边界 opaque 句柄的领域,见宿主边界。

注意

  • 别名声明在模块顶层;
  • 别名在类型注解位、泛型实参位、构造位都可用;is 测试按原类型回答;
  • typealias 是声明起始位的软关键字,val typealias = 1 这样的名字位照旧合法;退役的 type 已完全自由,作普通标识符用(val type = 7 合法)。
最后更新于 2026年10月8日