来源:http://www.typescriptlang.org/docs/handbook/basic-types.html
但是官网也有错的地方,比如never,我的typescript是2.3.4啊,最新的,怎么没这个语法呢???
/**练习typeScript-2 basicTypes * Created by liyanq on 17/6/8. */ /*1,Boolean就是基础类型,不是对象类型,和es5的Boolean构造函数两码事~ * 2,大写的是接口,小写的是基础类型.只有用Number.valueOf()才能和基础类型相加减~~ * 3,Just like JavaScript, TypeScript also uses double quotes (") or single quotes (') to surround string data. * */ //------Boolean-----// let isDone: boolean = false; console.log(isDone.toString()); // isDone = "H";//Type string is not assignable to type boolean //-----Number-------// let decimal: Number = 10;//10 let hex: Number = 0x10; //16 let binary: Number = 0b10;//2 let octal: Number = 0o10; //8 console.log(decimal.toFixed(2), hex.toString(2), binary.toExponential(2), octal.toPrecision(4));//10.00 10000 2.00e+0 8.000 //-----string------// let Name: String = "twelveMan"; // let name:String = "twelveMan";//cannot redeclare block-scope variable 'name'??? let age: Number = 34; let info = `${Name} ${age}`;//模版写法 console.log(info); //-----array-------// let list: Array<Number> = [1, 2, 3];//看到范型了~~ console.log(list.map(function (value) { return value.valueOf() + 1; }).join(";")); //-------Tuple------// /*如果前面声明类型了,后面的赋值就会检查类型,超出范围就不检查了~~*/ let t1: [Number,String,Boolean,Boolean] = [34, "twelveMan", false, true];//es5中,直接就是个数组.=> var t1 = [34, "twelveMan"]; t1[3] = true; t1[4] = "elevenMan"; t1[5] = "elevenMan"; t1[6] = "elevenMan"; t1[7] = "elevenMan"; t1[8] = false; console.log(t1); //------Enum-------// /*1,声明必须小写,转换成es5好复杂啊~~ * 2,如果不指定值的话,默认的就是上一个值+1,指定的话,就是指定的值 * 3,可重复,但值相同*/ enum Day {today = 5, tomorrow, afterTomorrow = 5} let e1: Day = Day.afterTomorrow; console.log(e1 === Day.today);//true // let e2: string = Day[1];//报错啊,官网的不准啊~ // console.log(e2); //------Any-------// /*1,es5本身就是any,这个语法没啥意义啊~*/ let notSure: any = 4; notSure = "maybe a string instead"; notSure = false; notSure = "maybe a string instead"; console.log(notSure); let list2: any[] = [1, true, "free"]; list2[1] = "hello"; console.log(list2);//[ 1, 'hello', 'free' ] //-----void-------// // function warnUser():void { // return "This is my warning message";the type string is not assignable to type void // } function warnUser():void { console.log("This is my warning message"); } warnUser(); let unusable:void = undefined; unusable = null; //Declaring variables of type void is not useful // because you can only assign undefined or null to them: //-------Null and Undefined------// //说了一大堆,先知道没这两个类型就行了 // let u: undefined = undefined; // let n: null = null; //-------Never----------// // function error(message: string):never {//Cannot find name never??官网也不靠谱啊~ // throw new Error(message); // return message; // } // console.log(error("ddd")); //----type assertions --------// /*1,如果someValue不是any类型(默认)的话,编译器会检查转型是否能成功~*/ let someValue: any = "this is a string"; let strLength: number = (<string>someValue).length; let strLength1: number = (someValue as string).length; console.log(strLength , strLength1);//16 16