美文网首页
TypeScript中的类型(1)

TypeScript中的类型(1)

作者: wayne1125 | 来源:发表于2019-06-15 15:41 被阅读0次

一、TypeScript简介

TypeScript是Javascript的一个超集,主要提供了类型系统和对ES6的支持,它由Microsoft开发,代码开源于GitHub上。

二、为什么使用TypeScript

  • TypeScript增加了代码的可读性与可维护性
  • TypeScript非常包容
  • TypeScript拥有活跃的社区

三、安装使用TypeScript

  • 全局安装命令 npm install -g typescript
  • 编译文件 tsc hello.ts
  • 约定文件以.ts为后缀,编写react时,以.tsx为后缀
  • 主流IDE中都支持TS,包括代码补全,接口提示,跳转转义,重构

四、hello world

  • 新建hello.ts文件

console.log('hello world');
var a:string = "1";

命令行执行tsc hello.ts生成相应hello.js文件

  • ts中var a:string = 1;在编译的时候会提示“error TS2322: Type '1' is not assignable to type 'string'”,但依然会在hello.js中生成相应代码,体现了ts的包容性。

五、TypeScript原始数据类型

  • string number boolean null undefined enum symbol
var str:string = '1';
var num:number = 1;
var bol:boolean = true;

var nul:null = null;
str = null;
num = null;
bol = null;
// null 是 string、number、boolean字子类型,故这三种类型可设置成null

var un:undefined = undefined;
str = undefined;
num = undefined;
bol = undefined;
// undefined 是 string、number、boolean字子类型,故这三种类型可设置成undefined
  • 空值一般采用void来表示,void可表示变量也可表示函数返回值
var callback = function ():void{  
}
var a:void = null

六、TypeScript中的任意值

  • 任意值(Any)用来表示允许赋值为任意类型
  • 声明一个变量为任意值之后,对它的任何操作,返回的内容类型都是任意值
  • 变量如果在声明的时候,未指定其类型,那么它会被识别为任意值类型
var an:any = 1;
an = '1';
an = true;
an = null;
an = undefined;

var a; // a被认为任意类型

七、TypeScript中的类型推论

  • TypeScript会依据类型推论(Type Inference)的规则推断出一个类型
var a = 1; // 当给一个变量赋值初始化的时候,如果没有指定类型,会根据初始值推导它的类型number
// a = '1' 会报错
  • 如果定义的时候没有赋值,不管之后有没有赋值,都会被推断成any类型而完全不被类型检查

相关文章

网友评论

      本文标题:TypeScript中的类型(1)

      本文链接:https://www.haomeiwen.com/subject/mbtcfctx.html