typescript是javascript的超集(这是官网说的),而javascript本身作为一个脚本语言决定了它做不了大东西,typescript的出现也就是为了解决这个问题。一个语言本身的限制越少,越做不了大东西,相反,则能做大东西。这里用东西这个词其实有点不合适,但意思应该到了。
使用typescript之前首先要安装编译器,因为.ts文件不能被直接识别,要将其转换为.js文件,typescript的出现并不是为了颠覆javascript,是为了增强它,当然,要颠覆javascript,那是不可能的(以后的以后那就说不定了,不知道什么时候了)。
安装
npm install -g typescript
编译命令
tsc demo
1.限制类型
js在声明变量时只需要var xxx就行了,写成什么就是什么,不用管什么类型,当然,这是很烂的语法,在Java,c等语言中如果这样写,会被打死的,ts对其做了限制
//限制类型为字符串 如果a不是字符串 ,在编译阶段就会报错
let a:string = '1';
let b = 6;
a = "test";
console.log(a+b);
编译后:
//限制类型
var a = '1';
var b = 6;
a = "test";
console.log(a + b);
//限制函数参数为number型 返回值也会number型
function sum(a:number,b:number):number{
return a+b;
}
sum(3,3);
编译后:
//限制函数参数为number型 返回值也会number型
function sum(a, b) {
return a + b;
}
sum(3, 3);
2.泛型-----指定内部东西的类型
// 泛型 -->指定内部的类型
let arr:Array<string|number>;
arr = [12,7,'test',98];
console.log(arr);
编译为:
// 泛型 -->指定内部的类型
var arr;
arr = [12, 7, 'test', 98];
console.log(arr);
//返回值 void空值
function hello(age: number,name:string):void{
console.log(`我叫${name},今年${age}岁`);
// return 1;
}
hello(15,'mianma');
// never从不会结束 (有点无聊的操作啊)
function ne():never{
while(true){}
}
ne();
//任意类型
let a:any=12;
let b:string=(<string>a);
3.枚举
//枚举
enum Gender{male,female};
let gen1:Gender=Gender.male;
if(gen1==Gender.male){
console.log('this is man');
}else{
console.log('this is female');
}
编译后:
//枚举
var Gender;
(function (Gender) {
Gender[Gender["male"] = 0] = "male";
Gender[Gender["female"] = 1] = "female";
})(Gender || (Gender = {}));
;
var gen1 = Gender.male;
if (gen1 == Gender.ma1e) {
console.log('this is man');
}
else {
console.log('this is female');
}
4.接口
//接口
interface Person {
firstName: string,
lastName: string
}
function greet(person: Person){
console.log(`欢迎${person.firstName} ${person.lastName}`);
}
let User = {firstName: 'lee',lastName: 'Bruse'};
greet(User);
编译后:
function greet(person) {
console.log("\u6B22\u8FCE" + person.firstName + " " + person.lastName);
}
var User = { firstName: 'lee', lastName: 'Bruse' };
greet(User);
5.类
class Student{
fullName:string;
constructor(public firstName,public middle, public lastName){
this.fullName = `${firstName} ${middle} ${lastName}`;
}
}
interface Person{
firstName: string,
lastName: string
}
function greet(person: Person){
console.log(`欢迎${person.firstName} ${person.lastName}`);
}
let User = new Student('lee','T','Bruse');
greet(User);
编译后:
var Student = /** @class */ (function () {
function Student(firstName, middle, lastName) {
this.firstName = firstName;
this.middle = middle;
this.lastName = lastName;
this.fullName = firstName + " " + middle + " " + lastName;
}
return Student;
}());
function greet(person) {
console.log("\u6B22\u8FCE" + person.firstName + " " + person.lastName);
}
var User = new Student('lee', 'T', 'Bruse');
greet(User);