一共7种,boolean,number,string,Array,enum,any,void
1.boolean
ts文件:
/*var isBoolean;//js定义变量*/
var isBoolean:boolean;/*ts同时指定数据类型*/
var isBoolean2:boolean = false;//可只指定false/true,默认是undefined
function tell(){
alert(isBoolean2);
}
tell();
但引入的是js文件:
<script src="boolean.js"></script>
2.number
ts:
var num:number = 10;
function tell(){
num++;
alert(num);//11
}
tell();
3.string
ts:
var str:string="m";
function tell(){
str+="m";
alert(str);//mm
}
tell();
4.Array
ts:
var list1:number[]=[1,2,3];//2种格式
var list2:Array<String> = ["m1","m2","mm"];
function tell(){
// alert(list1[0]);//1
alert(list2[2]);//mm
}
tell();
5.enum
ts写一个枚举类型:
ts:
enum Color{blue,red,green};//blue=0,red=1,green=2
对应js代码:
var Color;
(function (Color) {
Color[Color["blue"] = 0] = "blue";
Color[Color["red"] = 1] = "red";
Color[Color["green"] = 2] = "green";
})(Color || (Color = {}));
ts完整demo:
enum Color{blue,red,green};//blue=0,red=1,green=2
enum Color2{blue=1,red,green};//blue=1,red=2,green=3
enum Color3{blue=1,red=4,green=2};//blue=1,red=4,green=2
var colorName:string = Color[1];
var colorName2:string = Color2[1];
var colorName3:string = Color3[2];
function tell(){
alert(colorName);//red
alert(colorName2);//blue
alert(colorName3);//green
}
tell();
var c:Color=Color.green;//获得元素的下标
function tell2(){
alert(c);//2
}
tell2();
6.any
ts:
var notSure:any=10;//如果不是any而是别的数据类型,后面会报错,any就像js,没指定数据类型 var notSure;
notSure = "Hello";
notSure =false;
var list:any[]=[1,"mm",true];//var list=[1,"mm",true];
function tell(){
// alert(notSure);//false
alert(list[1]);//mm
}
tell();
7.void
function tell():string{
return "返回string类型";
}
function say():number{
return 5;
}
function tell1():void{//void不需要返回值
}