1. 类型别名

  1. type Name = string;
  2. type NameResolver = () => string;
  3. type NameOrResolver = Name | NameResolver;
  4. function getName(name: NameOrResolver): Name {
  5. if (typeof name === 'string') {
  6. return name;
  7. } else {
  8. return name();
  9. }
  10. }

上述示例中,使用type创建类型别名,类型别名常用语联合类型

2. 字符串字面量类型

  1. type EventNames = 'click' | 'scroll' | 'mousemove' | 'rclick' ;
  2. function handEvent(element: Element , e: EventNames){
  3. //do something
  4. console.log(e) ;
  5. }
  6. handEvent(document.getElementById('hello') , 'scroll') ;
  7. //编译出错
  8. handEvent(document.getElementById('world') , 'dbclick') ;
  9. //编译错误
  10. handEvent(document.getElementById('world') ,ype '"dbclick"' is not assignable to parameter of type 'EventNames'.

上述示例中,使用type定义一个字符串字面量类型EventNames,它只能取值定义的四种字符串中的一种。