/**
*一.typescript类型学习
*/
//1.1 number类型
let a:number;
a=123;
//这么写会报错,a="hello,world";
console.log(a);
//1.2 string类型
let b:string;
b="hello,world";
console.log(b);
//1.3 boolean类型
let c:boolean=true;
console.log(c);
//返回值类型 :number 可以不写
function addNew(a:number,b:number):number
{
return a+b;
}
addNew(100,200);
//1.4 联合类型
let e:boolean|string;
e=true;
console.log(e);
e="true";
console.log(e);
//1.5 any类型,和js一样,不再检测类型,不建议用
//let f;//等同于let f:any
let f:any;
f=1;
console.log(f);
f="haha";
console.log(f);
f=true;
console.log(f);
//1.6 类型转换方法1
let g1=f as string;
console.log("g1="+g1);
//类型转换方法2
let g2=<string> f;
console.log("g2="+g2);
//1.7 object类型表示一个Js对象,ts中一切皆对象
let o:object;
o={};
o=function(){};
//1.8 这么写就限定了o1对象只能由name和age两个属性构成的类型对象,加上?表示属性可选
let o1:{name:string,age?:number};
o1={name:"孙悟空",age:18};
console.log(o1);
o1={name:"猪八戒"};
console.log(o1);
//1.9 表示o2的类型,除了name之后,可以有任意多个任意类型的属性
let o2:{name:string,[propName:string]:any};
o2={name:"唐僧",age:28,sex:"男"}
console.log(o2);
//1.10 设置对象为函数类型
//o3是个函数类型对象
let o3:Function;
//o4是一个参数为number,string,返回值为string的函数类型对象
let o4:(a:number,b:string)=>string;
o4=function(p1,p2):string{
return p1+p2;
}
//1.11 数组声明 类型[] 或Array<类型>
let arr:string[];
arr=["a",'b',"c"];
console.log(arr);
console.log(arr[0]);
let arr1:number[];
arr1=[1,2,3]
console.log(arr1);
console.log(arr1[1]);
let arr2:Array<string>;
arr2=["haha","hi","great"]
console.log(arr2);
//1.12 元组,即固定长度的数组 [类型,类型...]
//表示数组里面有两个值,一个是string类型,一个是number类型
let y:[string,number];
y=["hi",123];
//1.13枚举
enum Gender{
Female=0,
Male=1
}
let person:{name:string,sex:Gender};
person={name:"张三",sex:Gender.Male};
console.log(person);
//1.14 类型的别名
type mytype=string|number;
let m:mytype;
m=1;
console.log("m="+m);
m="str";
console.log("m="+m);
//1.15 字面量类型,即取值只能是指定的值之一
let sex:"male"|"female";
sex="good";//这么写会报错,必须是male或者femal
sex="male";
sex="female";