现在的位置: 首页 > web前端 > 正文

TypeScript typeof 操作符

2020年07月09日 web前端 ⁄ 共 912字 ⁄ 字号 评论关闭

  本文示例的运行环境是TypeScript官网的Playground,对应的编译器版本是v3.8.3。


  typeof简介


  在TypeScript中,typeof操作符可以用来获取一个变量或对象的类型。


  interfacePerson{


  name:string;


  age:number;


  }


  constsem:Person={name:"semlinker",age:30};


  typeSem=typeofsem;//typeSem=Person


  在上面代码中,我们通过typeof操作符获取sem变量的类型并赋值给Sem类型变量,之后我们就可以使用Sem类型:


  constlolo:Sem={name:"lolo",age:5}


  你也可以对嵌套对象执行相同的操作:


  constkakuqo={


  name:"kakuqo",


  age:30,


  address:{


  province:'福建',


  city:'厦门'


  }


  }


  typeKakuqo=typeofkakuqo;


  /*


  typeKakuqo={


  name:string;


  age:number;


  address:{


  province:string;


  city:string;


  };


  }


  */


  此外,typeof操作符除了可以获取对象的结构类型之外,它也可以用来获取函数对象的类型,比如:


  functiontoArray(x:number):Array<number>{


  return[x];


  }


  typeFunc=typeoftoArray;//->(x:number)=>number[]


  TypeScript之const断言


  TypeScript3.4引入了一种新的字面量构造方式,也称为const断言。当我们使用const断言构造新的字面量表达式时,我们可以向编程语言发出以下信号:


  表达式中的任何字面量类型都不应该被扩展;


  对象字面量的属性,将使用readonly修饰;


  数组字面量将变成readonly元组。


  总之,TypeScript给大家简单的介绍了一些,希望大家多看看。

抱歉!评论已关闭.