TypeScript学习笔记

发布时间:2022-07-05 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了TypeScript学习笔记脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

环境搭建

1、安装node环境

2、安装tyPEscript,-g表示全局安装。

npm i typescript -g

3、安装完毕后查看typescript版本

tsc -v

编译配置

可以在typescript的配置文件tsconfig.json中配置编译选项。

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "strict": true,
    "alwaysStrict": true,
    "strictNullChecks": false, //设置后可以给变量赋值null或者undefined.
    "downlevelITeration": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2015",
    "module": "es2020",
    "lib": [
      "es2018",
      "dom"
    ]
  }
}
规则名称 解释
noImplicitAny 不允许变量或函数参数具有隐式any类型
noImplicitThis 不允许this上下文隐式定义
strictNullChecks 不允许出现nullundefined的可能性
strictPRopertyInitialization 验证构造函数内部初始化前后已定义的属性
strictBindCallApply bind, call, apply 更严格的类型检测
strictFunctionTypes 对函数参数进行严格逆变比较

当alwaysStrict设置为true时,以上6种约束全部生效。当然也可以在其后覆盖想要的规则,如:想要禁止strictNullChecks,可以在alwaysStrict后设置 strictNullChecks: false。

noImplicitAny

配置开启后,不允许隐式的any类型,如下代码将会编译失败。

testCompilerOptions(dto):void {
  console.LOG(dto.name);
}

需要显式定义dto的类型,然后使用。

interface IEmployee {
  name: string;
  id: number;
}
testCompilerOptions(dto: IEmployee):void {
  console.log(dto.name);
}

 

noImplicitThis

todo

 

strictNullChecks

todo

 

strictPropertyInitialization

todo

 

strictBindCallApply

todo

 

strictFunctionTypes

Todo

 

语法基础

标识符

标识符指变量、类、方法、接口、装饰器的名称,其命名规则如下:

1、以字母或下划线开头;

2、不能以数字开头;

3、不能包含特殊符号,下划线 _和美元符号 $除外;

4、不能以class、interface等作为标识符,但可以用类型名称如:string,number等作为标识符(不建议这样使用);

5、标识符大小写敏感;

如下这些都是合法的标识符。

testIdentifier(): void {
  let _a = 123;
  let _B = "abc";
  let a = 1;
  let $a = 2;
  let $ = 3;
  let a123="2333";
  let number: number = 123;
  let string: string = "abc";
  let class123: string = "abc";
  let inTerfAce123 ="ddd";
  console.log(string + class123 + number);
}

命名规范

typescript命名规范和javascript一致:

1、变量、方法都使用驼峰式;

2、名称空间、类名、接口名使用Pascal式(首字母大写)。

export class TestDto {
  private testId: number;
  private testName: string;
  
  public getName():string{
    return this.testName;
  }
  
  public setId(id: number):void{
    this.testId = id;
  }
}
export interface ITestInterface {
  toString():string;
}

 

变量

typescript是javascript的超集,所以typescript中定义变量也有这三种方式:VAR、let、const。

1、var定义全局变量,可以重复定义,后者覆盖前者(类型和值都可以覆盖)非必须不用

2、let定义局部变量,不可以重复定义,赋值后可以修改。

3、const定义局部变量,但变量值是readonly的,赋值后不能修改。

var x = 123;
​
@component({
  selector: 'app-nav',
  templateUrl: './nav.COMponent.htML',
  styleUrls: ['./nav.component.scss']
})
export class NavComponent {
  envName: string = "";
  constructor() {
  }
​
  testVariables():void {
    var x = 12; // x为全局变量,所以可以重复定义。
    x = "123 string";
    
    let x1 = 2;  //ts有类型推断,所以:number可省略。
    x1 = 2 //good,可以修改值。
    x1 = "string"; // error,不可以修改类型,一旦确定类型就不可以再改变。
    
    const x2 = 3;
    x2 = 4; //error,readonly类型变量,不能改变值。
  }
}

 

基原类型

typescript中的基原(primitive type)类型如下:

string

typescript中的string类型可以使用单引号或双引号,例如:

let name: string = "hello typescript";
//或者
let name: string = 'hello typescript';
​
let name: string ='hello typescript"; //error,要么全是单引号,要么全是双引号。
​

因为typescript具有类型推断功能,在给变量赋值时可以根据值来推断出变量的类型,所以可以省略显式的类型名称,以上代码可以简化如下:

let name = "hello typescript";

 

number

typescript没有像其它语言一样把数值类型细化成int、float、double,而是使用一个统一的类型名称number。

let employeeid: number = 123;
//或者
let employeeId = 123;

 

boolean

布尔类型,当typescript在非严格模式下("strictNullChecks": false),它总共允许4个值 true 、false、undefined、null.

布尔类型,当typescript在严格模式下("strictNullChecks": true)其值只能是true或flase。

//严格模式
let success: boolean = true;
let fail: boolean = false;
​
//非严格模式
let success: boolean = null;
let fail: boolean = undefined;

 

数组类型

数组类型有两种表示方法,一种是类型加[]如: 类型名称[],另外一种是Array<类型名称>。按照国际惯例,typescript数组的下标也是从0开始的。

let testArray:number[] = [1,2,3,4,5];
//或者
let testArray:Array<number> = [1,2,3,4,5];
//或者使用类型推断,省略显式的类型名称
let testArray = [1,2,3,4,5];
​
//下标从0开始
console.log(testArray[0]);
​
let strArray: string[] = ["a", "b", "c"];
//或者
const strArray: string[] = ["a", 'b', 'c']; //语法上没问题,但是不推荐单双引号混用。
console.log(strArray);

 

any

todo

 

never

todo

 

null

todo

 

undefined

todo

 

表达式

 

语句

typescript主要有变量声明语句,赋值语句,判断语句,循环语句。

变量声明

变量声明语句如 let index = 1; 可以以分号结束,也可以省略分号,建议总是以分号结束。

let index;
const a;
var gTest;
let testArray;
​
index = 1;
a = "test";
gTest = false;
testArray = []

 

变量赋值

省略

判断

if else

和其它编程语言一样,如下例所示:

let a = 90;
if(a>=60) {
  console.log("pass");
} else if(a<60){
  console.log("failed");
}

 

switch case

let color = "red";
switch(a){
  case "white":{
    console.log("compound color");
    break;
  }
  case "red": {
    console.log("primitive color");
    break;
  }
  case "green":{
    console.log("primitive color");
    break;
  }
  case "blue":{
    console.log("primitive color");
    break;
  }
  default:
    break;
}

 

循环

和其它主流编程语言一样,typescript也支持while和for循环语句。

while循环

let count = 10;
while(count < 1000){
  console.log(count);
  count++;
}

for循环

for(let index =0; index < 1000; index++){
  console.log(index);
}

for ... in 循环

let list = [11,22,23,34,65];
for(let item in list){
  console.log(item);
}
//上面循环输出数组下标:0,1,2,3,4

for ... of 循环

for...of 和 for...in 是有区别的。

let list = [11,22,23,34,65];
for(let item of list){
  console.log(item);
}
//上面循环输出数组元素值:11,22,23,34,65

 

名称空间

typescript名称空间 namespace用来约束类或者接口的访问范围,最明确的目的就是解决重名问题。

todo

 

类有字段和方法,默认情况下字段和方法均为public,这和C#刚好相反。如下需要设置成私有成员或方法,需要显式加上private修饰。

export class MyClass {
  private name: string;
  private age: number;
  
  //默认为public
  getName():string{
    return this.name;
  }
  
  //为了增加可读性,建议显式加上public修饰。
  public getAge(): number {
    return this.age;
  }
}

 

接口

相比其它面向对象的编程语言,typescript中的接口才是真正的接口,它既有形(成员字段)的约束又有行为(成员方法)的约束。

export interface IPerson{
  //形的约束
  name: string;
  age: number;
  color: string;
  race: string;
  height: number;
  weight: number;
  
  //行为的约束
  eat():void
  work():void
  walk():void
}

 

方法

typescript是javascript的超集,javascript支持的函数写法,在typescript文件中当然也是可以的。不过,这样的js函数需要放在ts的class之外,否则会被认为是ts的函数而编译报错。

export MyClass {
  //ts method
  testMethod():void{
    console.log("This is a ts method.");
  }
​
  //js function will get error here.
  function test(){
    console.log("This is a js function.");
  }
}
​
//js function
function sayHello(str){
  alert(str);
}

 

常用的一些集合方法有:foreach(), every(), some(), map(), reduce(), filter(),和C#中的linq扩展方法类似,这些方法的接收一个函数表达式(箭头函数或者叫lamba表达式)作为参数,通过注入不同的处理逻辑来实现相应的功能。

forEach()

forEach(), every()和some()本质不是循环语句,而是方法,其参数为一个函数表达或者叫箭头函数。forEach()方法没有返回值,every()和some()有返回值。

let list = [1,2,3,4,5];
list.forEach(x=> console.log(x));

every()

every() 有返回值。

let list = [1,2,3,4,5];
let result = list.every(x => {
  if(x>3){
    return true;
  }
});

some()

 

map()

//数组翻倍后求和
let myList:number[] = [12,3,44,12,3,23,33];
let result:number = myList.map(x=> x * 2).reduce((sum, x)=> sum + x, 0);
console.log(result);

reduce()

 

filter()

TypeScript中的Array.filter( lambada_exPression )类似C#中的Linq,例如: myList.Where( x=> x%2)

testFilter(): void {
  let myList: number[] = [12, 3, 44, 12, 3, 23, 33];
  myList.filter(x => x % 2 == 0).forEach(x=> console.log(x));
}

 

装饰器

装饰器(Decorator)是一种特殊类型的声明,它能够被附加到类声明,方法, 访问符,属性或参数上。 装饰器使用 @expression这种形式,expression求值后必须为一个函数,它会在运行时被调用,被装饰的声明信息做为参数传入。

@Component({
  selector: "app-nav",
  templateUrl: "./nav.component.html",
  styleUrls: ["./nav.component.scss"]
})
export class NavComponent {
  constructor() {
  }
}

这里的@Component就是一个装饰器,它接收一个对象作为参数。加注了@Component的类就是一个Angular的Component了,这和Java的注解类似。

 

高级特性

反射

testReflect():void {
  let myData:any = {
  "propertyA": 1,
  "propertyB": "test123",
  "propertyC": ["C#", "C++", "Java", "JavaScript", "Python"],
    "sayHello": function(s:string){
      console.log(s);
    },
      "toString": function(){
        return this.propertyA + " " + this.propertyB
      }
  }
​
  //reflect myData property and methods.
  for(let p in myData) {
    if(myData[p] instanceof Function) {
      console.log("function: " + p);
    } else {
      console.log("property: " + p);
    }
  }
}

运行结果为:

property: propertyA
property: propertyB
property: propertyC
function: sayHello
function: toString

脚本宝典总结

以上是脚本宝典为你收集整理的TypeScript学习笔记全部内容,希望文章能够帮你解决TypeScript学习笔记所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。