TypeScript是微软开发的一个JavaScript的超集,个人感觉就是基于Js之上增加更多强类型约束与检查机制,是一个严格模式模式下的严格Js(禁止套娃)。特别是对于熟悉后台开发的同志,很多地方都会触发共鸣(特别是C#开发者,毕竟TypeScript是微软推出的,当然会有亲儿子的影子)。但是在学习TypeScript之前呢,最好要有JavaScript和ES6知识的基础,不然磕磕碰碰的学会打消积极性的。废话少说,开始水博客,这里记录本人学习ts路上的一些笔记,本人主要是根据官方文档和中文官网一篇篇看下来的,中途无意间撞见阮一峰大佬的教程觉得挺不错的,推荐想快速入门的同志们参考。
1 //1. 数字类型 2 let age: number = 28; 3 /* ---------------------------------------------------------------------- */ 4 //2. 字符串 5 let fname: string = "Alice"; 6 // 模板字符串 7 let greet: string = `Hello ,my name is ${fname}, i am ${age} years old`; 8 console.log("string类型:", greet); 9 /* ---------------------------------------------------------------------- */ 10 //3. 数组类型 11 let list1: number[] = [1, 2, 3, 4, 5]; 12 let list2: Array<string> = ["Alice", "Bob", "John"]; 13 console.log("数组类型1 :", list1); 14 console.log("数组类型2 :", list2); 15 /* ---------------------------------------------------------------------- */ 16 //4. 元组类型 17 let card: [string, number]; 18 card = [fname, age]; 19 console.log("元组类型:", card); 20 console.log("元组可按索引访问 card[0]:", card[0]); 21 console.log("元组可按索引访问 card[1]:", card[1]); 22 /* 23 下面这个写法ts会报错,但是js可以通过并且正常运行 24 card[3] = ‘world‘; 25 console.log("元组类型:", card); 26 */ 27 /* ----------------------------------------------------------------------- */ 28 //5. 枚举类型 29 enum Gender { 30 Female = 0, 31 Male 32 } 33 let gender: Gender = Gender.Female; 34 console.log("枚举类型 gender:", gender); 35 /* ----------------------------------------------------------------------- */ 36 //6. Any类型 37 let file: any = 123456789; 38 file = "Quis labore excepteur aliqua aliquip." 39 file = false; 40 //file.ifItExists(); // okay, ifItExists might exist at runtime 41 //file.toFixed(); // okay, toFixed exists (but the compiler doesn‘t check) 42 let repo: any[] = [1, "Nisi reprehenderit qui irure dolor sunt culpa occaecat.", false]; 43 console.log("any数组类型,repo[1]: ", repo[1]); 44 /* ----------------------------------------------------------------------- */ 45 //7. void类型 46 function warnUser(): void { 47 console.log("This is my warning message"); 48 } 49 //声明一个void类型的变量没有什么大用,因为你只能为它赋予undefined和null 50 let unusable: void = undefined; 51 /* ----------------------------------------------------------------------- */ 52 /*8. nerver类型:表示的是那些永不存在的值的类型 53 never类型是那些总是会抛出异常或根本就不会有返回值的函数表达式的返回值类型 54 下面3个函数为常见的返回值类型为never的函数*/ 55 //(1)无法达到的终点的函数返回类型是 never 56 function infiniteLoop(): never { 57 while (true) { 58 } 59 } 60 //(2)抛出异常的函数也是一种无法到达“终点”的函数,所以返回类型也是 never 61 function error(message: string): never { 62 throw new Error(message); 63 } 64 //(3)智能推断的返回值类型为never 65 function fail() { 66 return error("Something failed"); 67 } 68 /* ----------------------------------------------------------------------- */ 69 /*9. object 类型 70 object表示非原始类型,也就是除number,string,boolean,symbol,null或undefined之外的类型。 71 */ 72 let person: object = { 73 fname: fname, 74 age: age, 75 gender: gender, 76 card: card 77 } 78 function Greet(p: object | null): void { 79 if (p == null) { 80 console.log("Hello everyone!"); 81 } 82 // let name = p.fname; 83 // let age = p.age; 84 // console.log(`Hello ,my name is ${name}, i am ${age} years old`); 85 }; 86 Greet(null); 87 Greet(person); 88 // Greet(fname); //报错 89 /* ----------------------------------------------------------------------- */ 90 /*10. 类型断言,类似与其他语言中的强制类型转换 */ 91 let someValue: any = "this is a string"; 92 //写法一: 93 let strLength: number = (<string>someValue).length; 94 console.log("strLength:", strLength); 95 //写法二:用as 96 strLength = (someValue as string).length; 97 console.log("strLength:", strLength);
1 /*------------------------------1.函数声明----------------------------------*/ 2 //1.1 为函数定义类型 3 function add(x: number, y: number): number { 4 return x + y; 5 } 6 let myAdd = function (x: number, y: number): number { 7 return x + y; 8 } 9 let myAddFunc = (x: number, y: number): number => x + y; 10 11 let [x, y] = [1, 2]; 12 console.log(`add : ${x} + ${y} = `, add(x, y)); 13 console.log(`myAdd: ${x} + ${y} = `, myAdd(x, y)); 14 console.log(`myAddFunc: ${x} + ${y} = `, myAddFunc(x, y)); 15 16 //1.2 书写完整函数类型 17 let myCompleteAddFunc: (baseValue: number, increment: number) => number 18 = function (x: number, y: number): number { 19 return x + y; 20 } 21 console.log(`myCompleteAddFunc: ${x} + ${y} = `, myCompleteAddFunc(x, y)); 22 /*--------------------------------------------------------------------------*/ 23 24 /*------------------------------2.可选参数-----------------------------------*/ 25 function buildName(firstName: string, lastName?: string) { 26 if (lastName) 27 return firstName + " " + lastName; 28 else 29 return firstName; 30 } 31 let result1 = buildName("Bob"); 32 let result2 = buildName("Bob", "Adams"); 33 /*--------------------------------------------------------------------------*/ 34 35 /*------------------------------3.默认参数-----------------------------------*/ 36 function buildName2(firstName: string, lastName = "Smith") { 37 return firstName + " " + lastName; 38 } 39 let result3 = buildName("Bob"); 40 let result4 = buildName("Bob", undefined); 41 let result5 = buildName("Bob", "Adams"); 42 /*--------------------------------------------------------------------------*/ 43 44 /*------------------------------4.剩余参数-----------------------------------*/ 45 function AddMany(...numbers: number[]) { 46 let sum = 0; 47 for (let index = 0; index < numbers.length; index++) { 48 sum += numbers[index]; 49 } 50 return sum; 51 } 52 let [w, z] = [3, 4]; 53 console.log(`AddMany ${x}+${y}+${w}+${z} = `, AddMany(x, y, z, w)); 54 /*--------------------------------------------------------------------------*/ 55 56 /*------------------------------5.箭头函数-----------------------------------*/ 57 // 注意:箭头函数能保存函数创建时的 this值,而不是调用时的值 58 let deck = { 59 suits: ["hearts", "spades", "clubs", "diamonds"], //[红,黑,草,方] 60 cards: Array(52), // 不带大小王的哦 61 createCardPicker: function () { 62 // 在使用箭头函数后,下面的这个this指代的就是deck这个对象了 63 return () => { 64 let pickedCard = Math.floor(Math.random() * 52); 65 let pickedSuit = Math.floor(pickedCard / 13); 66 67 return { suit: this.suits[pickedSuit], card: pickedCard % 13 }; 68 } 69 } 70 } 71 let cardPicker = deck.createCardPicker(); 72 let pickedCard = cardPicker(); 73 console.log("你拿到的牌是: " + pickedCard.card + " of " + pickedCard.suit); 74 /*--------------------------------------------------------------------------*/ 75 76 /*------------------------------6.函数重载----------------------------------*/ 77 let suits = ["hearts", "spades", "clubs", "diamonds"]; 78 //重载的话先把可能遇到的参数类型先一一列举出,再用最后一个使用any参数的函数囊括各个情况,具体实现每种参数情况下的处理方式 79 function pickCard(x: { suit: string; card: number; }[]): number; 80 function pickCard(x: number): { suit: string; card: number; }; 81 function pickCard(x: any): any { 82 // 如果传入的是一个对象或者数组,也就是用户传进来的就是几张牌,这样的话我们就从中抽一张 83 if (typeof x == "object") { 84 let pickedCard = Math.floor(Math.random() * x.length); 85 return pickedCard; 86 } 87 // 传入的是一个数组的话,就根据这个数抽一张牌 88 else if (typeof x == "number") { 89 let pickedSuit = Math.floor(x / 13); 90 return { suit: suits[pickedSuit], card: x % 13 }; 91 } 92 } 93 let myDeck = [{ suit: "diamonds", card: 2 }, { suit: "spades", card: 10 }, { suit: "hearts", card: 4 }]; 94 let pickedCard1 = myDeck[pickCard(myDeck)]; 95 console.log("你拿到的牌是: " + pickedCard1.card + " of " + pickedCard1.suit); 96 97 let pickedCard2 = pickCard(18); 98 console.log("你拿到的牌是: " + pickedCard2.card + " of " + pickedCard2.suit); 99 /*--------------------------------------------------------------------------*/
1 /*如果学习过C# 或 Java等,对这中Class的写法应该很熟悉*/ 2 /*---------------------------------1.类------------------------------------*/ 3 //1.1 定义一个类 4 //tips: 在ts中,类中变量和方法的默认访问修饰符是public 5 class Person { 6 //局部变量 7 protected readonly name: string; 8 protected readonly age: number; 9 private phone: string = "138555555555"; 10 private address: string = "221B Baker St"; 11 12 //构造函数 13 constructor(name: string, age: number) { 14 this.name = name; 15 this.age = age; 16 } 17 /* 上面的简化写法:在一个地方定义并初始化一个成员 18 constructor(readonly name: string,readonly age: number) { 19 } 20 */ 21 22 //存取器(属性) 23 get contact(): string { 24 return `${this.phone}—${this.address}`; 25 } 26 set contact(newVal: string) { 27 if (newVal && newVal.includes("—")) { 28 [this.phone, this.address] = newVal.split("—"); 29 } 30 else { 31 console.log("Incorrect format"); 32 } 33 } 34 //方法 35 greet() { 36 console.log(`Hi, i am ${this.name}`); 37 } 38 } 39 //1.2 创建一个类的实体 40 let sherlock = new Person("sherlock", 24); 41 sherlock.greet(); 42 //读属性 43 console.log(sherlock.contact); 44 //写属性 45 sherlock.contact = "13966666666—211B Baker St" 46 //再读新属性 47 console.log(sherlock.contact); 48 /*--------------------------------------------------------------------------*/ 49 50 /*---------------------------------2.继承------------------------------------*/ 51 //2.1 继承类的关键字:extends 52 class Doctor extends Person { 53 diagnose() { 54 console.log(`diagnose illness...`) 55 } 56 } 57 58 //如果子类也有自己的构造函数,那么还必须要调用父类的构造函数,写法就是super() 59 class Teacher extends Person { 60 private school: string; 61 constructor(name: string, age: number, school: string) { 62 super(name, age); 63 this.school = school; 64 } 65 teach() { 66 console.log(`teach at ${this.school} ...`); 67 } 68 } 69 70 //2.2 创建子类 71 let Alice = new Doctor("Alice", 28); 72 Alice.greet(); 73 Alice.diagnose(); 74 75 let Howard: Teacher = new Teacher("Howard", 35, "Kw HighSchool"); 76 Howard.greet(); 77 Howard.teach(); 78 /*---------------------------------------------------------------------------------------*/ 79 80 /*---------------------------------------3.抽象类-----------------------------------------*/ 81 //给其他类来继承的,不能创建一个抽象类的实例 82 abstract class Animal { 83 abstract makeSound(): void; //抽象类的抽象方法我们不需要实现,关键字:abstract 84 85 move(): void { 86 console.log(‘roaming the earch...‘); 87 } 88 } 89 //定义抽象类的派生类 90 class Dog extends Animal { 91 makeSound(): void { 92 console.log(‘wong wong wong...‘); 93 } 94 95 eat(): void { 96 console.log(‘happiness...‘) 97 } 98 } 99 100 let xiaobai: Animal; // 允许创建一个对抽象类型的引用 101 xiaobai = new Dog(); // 允许对一个抽象子类进行实例化和赋值 102 xiaobai.makeSound(); 103 //xiaobai.eat(); //Error :因为声明的是Animal类型,Dog类的方法无法调用到 104 105 /*--------------------------------------------------------------------------------------*/
1 //接口作用的简单总结:定义契约 2 3 /*-------------------------------1.接口的作用----------------------------------*/ 4 interface LabelledValue { 5 label: string; 6 } 7 8 function printLabel(labelledObj: LabelledValue) { 9 console.log(labelledObj.label); 10 } 11 12 let myObj = { size: 10, label: "Size 10 Object" }; 13 printLabel(myObj); 14 /*---------------------------------------------------------------------------*/ 15 16 17 /*-------------------------------2.可选参数------------------------------------*/ 18 interface SquareConfig { 19 color?: string; //加上 ? 就表示参数是可选的了 20 width?: number; 21 } 22 23 function createSquare(config: SquareConfig): { color: string; area: number } { 24 let newSquare = { color: "white", area: 100 }; 25 if (config.color) { 26 newSquare.color = config.color; 27 } 28 if (config.width) { 29 newSquare.area = config.width * config.width; 30 } 31 return newSquare; 32 } 33 34 let mySquare = createSquare({ color: "black" }); 35 /*---------------------------------------------------------------------------*/ 36 37 /*----------------------------3.函数类型的接口---------------------------------*/ 38 /* 刚刚上面使用接口去约束了参数的形式,接口也可以约束函数的形式 39 */ 40 41 interface SearchFunc { 42 (source: string, subString: string): boolean; 43 } 44 45 /* 46 ① 参数名称不是强制一样的,只要参数类型相同即可 47 ② 实现接口的方法,如果不指定参数类型,TypeScript的类型系统会推断出参数类型 48 */ 49 let mySearch: SearchFunc; 50 mySearch = function (src, sub) { 51 let result = src.search(sub); 52 return result > -1; 53 } 54 /*---------------------------------------------------------------------------*/ 55 56 /*----------------------------4.可索引类型接口----------------------------------*/ 57 interface IArray { 58 [index: number]: string 59 } 60 61 var myArr: IArray = ["jack", "john", "jim"]; 62 63 interface IObj { 64 [index: string]: string 65 } 66 67 var myObject: IObj = { name: "jack", email: "123@126.com" }; 68 /*----------------------------------------------------------------------------*/ 69 70 /*-------------------------------5.类类型接口----------------------------------*/ 71 //定义一个接口来约束一个英雄该有的内涵,嘿嘿 72 interface IHero { 73 position: heroType; 74 level: number; 75 heroName: string; 76 phrase: string; 77 attack(): void; 78 } 79 enum heroType { 80 warrior, 81 wizard, 82 archer, 83 tank, 84 assassin 85 } 86 //定义类型实现接口IHero,关键字“implements” 87 class Hero implements IHero { 88 position: heroType; 89 level: number; 90 heroName: string; 91 phrase: string; 92 constructor(pos: heroType, lev: number, name: string, phrase: string) { 93 this.position = pos; 94 this.level = lev; 95 this.heroName = name; 96 this.phrase = phrase; 97 } 98 attack(): void { 99 console.log(`${this.phrase}!!!`); 100 } 101 } 102 let yasuo: Hero = new Hero(heroType.warrior, 1, "疾风剑豪", "ha sa ki"); 103 yasuo.attack(); 104 /*---------------------------------------------------------------------------*/
原文:https://www.cnblogs.com/xhy0826/p/12722631.html