移动测试开发 为什么要学习 TypeScript

opentest-oper@360.cn · 2020年09月03日 · 671 次阅读

一、什么是 TypeScript?

根据微软官方的定义,TypeScript 是 JavaScript 的一个超集。TypeScript 是一门不同于 JavaScript 的新语言,但它可以编译成 javascript 在浏览器中运行。

二、我们为什么要学习 TypeScript

*TypeScript 三大优势 *

1.支持 ES6 规范
2.强大的 IDE 支持
3.Angular2 的开发语言

三、TypeScript 中的数据类型

TypeScript 中包含了 es6 中的所有数据类型

布尔值 - boolean , 数字 - number ,字符串 - string ,数组 - Array ,元组 - Tuple ,函数 - Function , 对象 - Object ,操作符 - void
Symbol - 具有唯一的值 ,undefined 和 null 初始化变量 ,any - 如果不指定一个变量的类型,则默认就是 any 类型 , never - never 表示永远不会有返回值的类型 1.函数抛出异常 2. 死循环

四、TypeScript 中的枚举类型

枚举的类

数字枚举:使用枚举可以定义一些有名字的数字常量,枚举类型会被编译成一个双向映射的对象。枚举成员会被赋值为从 0 开始递增的数字,同时,也会被枚举值到枚举名进行反向映射。

字符串枚举:字符串枚举是不可以做双向映射的。

异构枚举:把数字枚举和字符串枚举混用,就形成了异构枚举,这种方式很容易引起混淆,不推荐使用

枚举成员

const enum(常量枚举):
1.没有设置初始值
2.对已有枚举成员的引用
3.常量的表达式

computed enum(需要计算的枚举成员):这些枚举成员的值不会在编译阶段计算,而是保留到程序的执行阶段

常量枚举

常量枚举其实就是是在 enum 关键字前使用 const 修饰符

常量枚举会在编译阶段被移除

作用:当我们不需要一个对象,而需要对象的值,就可以使用常量枚举,这样就可以避免在编译时生成多余的代码和间接引用

常量枚举成员在使用的地方被内联进来,且常量枚举不可能有计算成员

五、TypeScript 的接口

TypeScript 并没有 “实现” 接口这个概念,而是只关注值的外形,只要传入的对象满足上面的必要条件,那么它就是被允许的。

对象类型接口

interface List {
  id: number;
  name: string;
}

interface Result {
  data: List[];
}

function getResult(result: Result) {
  result.data.forEach(item => {
    console.log(item.id, item.name);
  })
}

let myResult = {
  data: [
    {id: 1, name: 'Bob', score: 98}, 
    {id: 2, name: 'Carl', score: 87}
  ] 
};

getResult(myResult);

// 1 'Bob'
// 2 'Carl'

类型检查器会查看 getResult 的调用,其传入的参数中包含了三个属性,但是编译器只会检查那些必需的属性是否存在,且其类型是否匹配。所以即使多了一个 score 属性,也是可以通过编译的。

但是当 getResult 参数传入的是对象字面量,ts 不仅会检查必要的属性,还会对额外的参数进行类型检查。

interface list {
 id:number;
 name:string;
}

interface Result {
 data List [];
}

function getResult(result:Result) {
 result.data.forEach(item =>{
   console.log(item.id, item.name)
 })

getResult({
  data:[
   { id : 1 , name:'Bob', score:98 },
   { id : 2 , name:'Carl', score:87 },
 ]
});

}

除了把对象字面量赋值给一个变量外,还有 3 种方法绕过这种检查:

1.使用类型断言
2.可选属性:在属性名字后面加一个?符号
3.字符串索引签名

索引类型

可索引类型具有一个索引签名,它描述了对象索引的类型,还有相应的索引返回值类型。比如:a[0] 或 a["name"]

//定义格式:
interface 接口名 {
  [任意字段: 索引类型]: 索引返回值类型;
}

索引签名可以是字符串和数字也可以同时使用两种类型的索引

// 数字索引
interface StringArray {
  [inder: number]: string;
}

let s1: StringArray = ["TypeScript", "Webpack"];
console.log('s1: ', s1);   // s1:  [ 'TypeScript', 'Webpack' ]

// 字符串索引
interface ScoreMap {
  [subject: string]: number;
}

let s2: ScoreMap = {
  "Chinese": 99,
  "Math": 100
}
console.log('s2: ', s2);   // s2:  { Chinese: 99, Math: 100 }

// 同时使用字符串和数字索引
interface StudentMap {
  [index: number]: string;
  [name: string]: string;
} 

let s3: StudentMap[] = [
  {
    1: "678分",
    "姓名": "张伟"
  },
  {
    2: "670分",
    "姓名": "尔康"
  }
]
console.log('s3: ', s3);
// s3:  [ { '1': '678分', '姓名': '张伟' }, { '2': '670分', '姓名': '尔康' } ]

如果同时使用字符串索引和数字索引,要么数字索引的返回值类型和字符串索引返回值类型没有继承关系 ,要么数字索引的返回值必须是字符串索引返回值类型的子类型。因为当使用 number 来索引时,js 会将它隐式转换成 string,然后再去索引对象。

class Animal {
  name: string;
}

class Dog extends Animal {
  breed: string;
}

interface Okay {
  [x: string]: Animal;
  [y: number]: Dog;
}

// Numeric index type 'Animal' is not assignable to string index type 'Dog'.
interface NotOkay {
  [x: string]: Dog;
  [y: number]: Animal;  // 数字索引类型“Animal”不能赋给字符串索引类型“Dog”
}

只读属性

interface Point {
  readonly x: number;
  readonly y: number;
}

// 可以通过赋值一个对象字面量来构造一个Point。 赋值后,x和y再也不能被改变了。
let p: Point = { x: 3, y: 5};
console.log('p', p);   // p { x: 3, y: 5 }

// p.x = 20;   // Cannot assign to 'x' because it is a read-only property

可以在属性名前用 readonly 来指定只读属性

TypeScript 具有 ReadonlyArray 类型,它与 Array 相似,只是把所有可变方法都去掉了。可以确保数组创建后就再也不能修改。

let arr: number[] = [1, 2, 3];
let ro: ReadonlyArray<number> = arr;

ro[0] = 33;   // 类型“readonly number[]”中的索引签名仅允许读取
ro.push(4);   // 类型“readonly number[]”上不存在属性“push”
ro.length = 99;  // Cannot assign to 'length' because it is a read-only property

判断该使用 readonly 还是 const 的方法主要是看作为变量还是作为属性,作为变量的话使用 const,作为属性则使用 readonly 函数类型接口
接口还可以用来限制函数的 参数列表 和 返回值类型 。

interface Add {
  (base: number, increment: number): number
}

// 调用接口
let add: Add = (x: number, y: number) => x + y;
console.log( add(1, 2) );   // 3

类类型接口

TypeScript 中的类可以像 Java 里的接口一样,使用类来实现一个接口,由此来明确的强制一个类去符合某种契约。

interface ClockInterface {
  currentTime: Date;
}

class Clock implements ClockInterface {
  currentTime: Date;
  constructor(h: number, m: number) {}
}

也可以在接口中描述一个方法,在类里实现它

interface ClockInterface {
  currentTime: Date;
  setTime(d: Date):
}

class Clock implements ClockInterface {
  currentTime: Date;
  setTime(d: Date) {
    this.currentTime = d;
  }
  constructor(h: number, m: number) {}
}

混合类型接口

interface Counter {
    (start: number): string;
    interval: number;
    reset(): void;
}

var c: Counter;
c(10);
c.reset();
c.interval = 5.0;

继承接口

接口也可以相互继承,可以从一个接口里复制成员到另一个接口里,由此可以更加灵活的将接口分割到可重用的模块里

interface Shape {
  color: string;
}

interface Square extends Shape {
  sideLength: number;
}

let square: Square = {
  color: 'red',
  sideLength: 15
}

console.log('square ', square);   // square  { color: 'red', sideLength: 15 }

一个接口可以继承多个接口,创建出多个接口的合成接口

interface Shape {
  color: string;
}

interface PenStroke {
  penWidth: number
}

interface Square extends Shape, PenStroke {
  sideLength: number;
}

let square: Square = {
  color: 'red',
  penWidth: 6,
  sideLength: 15
}

console.log('square ', square);   // square  { color: 'red', penWidth: 6, sideLength: }

六、TypeScript 中的函数定义

函数的定义方式

// (1)、命名函数
function add1(x: number, y: number): number {
  return x + y;
}

// (2)、匿名函数
let add2:(x: number, y: number) => number = function(x: number, y: number) {
  return x + y;
}

// (3)、类型别名
type add3 = (x: number, y: number) => number

// (4)、接口
interface add4 {
  (x: number, y: number): number
}

TypeScript 中形参和实参的类型和数量必须一一对应

function add(x: number, y: number) {
  return x + y;
}

add(1, 2);
add(1, 2, 3);   // 应有 2 个参数,但获得 3 个
add('1', 2);    // 类型“"1"”的参数不能赋给类型“number”的参数
add(1);         // 应有 2 个参数,但获得 1 个

可选参数

TypeScript 中我们可以在参数名后面使用 ? 实现可选参数的功能,可选参数必须跟在必须参数后面

function add(x: number, y?: number) {
  return y ? x + y : x
}
add(1);

// error: 必选参数不能位于可选参数后
function add2(x: number, y?: number, z: number) {
  return x + y + z;
}

默认参数

TypeScript 中我们也可以为参数提供一个默认值,使用默认参数需注意两点:

1.如果带默认值的参数出现在必须参数之前,必须手动传入 undefined 来获得默认值
2.如果带默认值的参数后面没有必须参数,则无须传入任何内容就可以获得默认值

function add(a: number, b=1, c: number, d=2) {
  return a + b + c + d;
}

console.log(add(3, undefined, 4));  // 10 (3+1+4+2)
console.log(add(1, 2, 3, 4));       // 10 (1+2+3+4)
console.log(add(1, 2, 3));          // 8  (1+2+3+2) 
console.log(add(1,2));   // Expected 3-4 arguments, but got 2.

剩余参数
剩余参数会被当做个数不限的可选参数,需要放在参数列表的最后面

function add1(x: number, ...restParams: number[]) {
  return x + restParams.reduce((pre, cur) => pre + cur)
}

console.log(add1(1, 2, 3, 4));    // 10

函数重载

所谓重载,指的是不同函数使用相同的函数名,但是函数的参数个数或类型不同,返回类型可以相同也可以不同。调用的时候,根据函数的参数来区别不同的函数
重载的好处是不需要为了功能相近的函数使用选用不同的函数名称,以此来提高函数的可读性
TypeScript 中的重载要求我们先定义一系列名称相同的函数声明(即重载列表),并且在定义重载的时候,一定要把最精确的定义放在前面。

function overload(...restParams: number[]): number;

function overload(...restParams: string[]): string;

function overload(...restParams: any[]) {
  let firstParam = restParams[0];
  if(typeof firstParam === 'number') {
    return restParams.reduce((prev, curr) => prev + curr);
  }
  if(typeof firstParam === 'string') {
    return restParams.join('');
  }
}

console.log('传入数字参数,返回求和: ', overload(1, 2, 3));
// 传入数字参数,返回求和:  6

console.log('传入字符参数,返回拼接: ', overload('a', 'b', 'c'));
// 传入字符参数,返回拼接:  abc

总结

还有许多我觉得比较平常的点就没有列出来,比如支持类型别名,泛型,协变逆变双变等等,这只是开始学习的第一步。

TypeScript 的好处很明显,在编译时就能检查出很多语法问题而不是在运行时,避免低级 bug。不过由于是面向对象思路,有没有需求使用 Typescript,我觉得写出代码是否易于维护、优雅,不在于用了什么框架、语言,在于开发者本身的架构思路。诚然好的框架和语言能间接帮助开发者写出规范的代码。所以如果 Typescript 能使团队易于协同开发,提高效率。

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
暂无回复。
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册