TypeScript入门语法(下)

(续上)

八、数组

1、解构

let x: number; let y: number; let z: number;
let array = [0,1,2,3,4];
[x,y,z] = array;

2、展开运算符

let two_array = [0, 1];
let five_array = [...two_array, 2, 3, 4];

3、遍历 for(let i of arr){...}

let colors: string[] = ["red", "green", "blue"];
for (let i of colors) {
  console.log(i);
}

九、对象

1、解构

let person = {
  name: "Semlinker",
  gender: "Male",
};
let { name, gender } = person;

2、展开运算符

let person = {
  name: "Semlinker",
  gender: "Male",
  address: "Xiamen",
};
// 组装对象
let personWithAge = { ...person, age: 33 };
// 获取除了某些项外的其它项
let { name, ...rest } = person;

十、接口

TS的接口可用于对类的一部分行为进行抽象,也常用于对「对象的形状」进行描述。

1、对象的形状

interface Person {
  name: string;
  age: number;
}

let Semlinker: Person = {
  name: "Semlinker",
  age: 33,
};

2、可选 / 只读属性

interface Person {
  readonly name: string;
  age?: number;
}
// 还有ReadonlyArray属性,确保数组创建后不能再被修改。
let ro: ReadonlyArray = a;

十一、类

类——描述了所创建的对象共同的属性和方法。

1、类的属性和方法——Class

class Greeter {
  static cname: string = "Greeter";    // 静态属性
  greeting: string;    // 成员属性
  constructor(message: string) {    // 构造函数 - 执行初始化操作
    this.greeting = message;
  }
  static getClassName() {   // 静态方法,相当于Greeter.getClassName
    return "Class name is Greeter";
  }
  greet() {   // 成员方法,相当于es5的Greeter.prototype.greet=function(){...}
    return "Hello, " + this.greeting;
  }
}
let greeter = new Greeter("world");

2、访问器

通过 getter 和 setter 方法来实现数据的封装和有效性校验,防止出现异常数据。

3、类的继承

类的继承,是一个类(称为子类、子接口)继承另外的一个类(称为父类、父接口)的功能,并可以增加它自己的新功能的能力。在TS中使用extends来实现。

class Animal {
  name: string;
  constructor(theName: string) {
    this.name = theName;
  }
  move(distanceInMeters: number = 0) {
    console.log(`${this.name} moved ${distanceInMeters}m.`);
  }
}
class Snake extends Animal {
  constructor(name: string) {
    super(name);
  }
  move(distanceInMeters = 5) {
    console.log("Slithering...");
    super.move(distanceInMeters);
  }
}
let sam = new Snake("Sammy the Python");
sam.move();

4、 ECMAScript 私有字段

以#开头,每个私有字段名称都唯一地限定于其包含的类;
不能在私有字段上使用 TypeScript 可访问性修饰符(如 public 或 private);
私有字段不能在包含的类之外访问,甚至不能被检测到。

class Person {
  #name: string;
  constructor(name: string) {
    this.#name = name;   
  }
  greet() {
    console.log(`Hello, my name is ${this.#name}!`);
  }
}
let semlinker = new Person("Semlinker");
semlinker.#name;

十二、泛型

泛型是允许同一个函数接受不同类型参数的一种模板,可用来创建可复用的组件。

1、泛型接口

interface GenericIdentityFn {
  (arg: T): T;
}

2、泛型类

class GenericNumber {
  zeroValue: T;
  add: (x: T, y: T) => T;
}

let myGenericNumber = new GenericNumber();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function (x, y) {
  return x + y;
};

3、泛型变量

T(Type):表示一个 TypeScript 类型
K(Key):表示对象中的键类型
V(Value):表示对象中的值类型
E(Element):表示元素类型

4、泛型工具类型

(1)typeof——获取一个变量声明或对象的类型
(2)keyof——获取一个对象中的所有key值
interface Person {
    name: string;
    age: number;
}
type K1 = keyof Person; // "name" | "age"
(3)in——遍历枚举类型
type Keys = "a" | "b" | "c"
type Obj =  {
  [p in Keys]: any
} // -> { a: any, b: any, c: any }
(4)infer——声明类型变量并使用
type ReturnType = T extends (
  ...args: any[]
) => infer R ? R : any;
(5)extends——添加约束
interface ILengthwise {
  length: number;
}
function loggingIdentity(arg: T): T {
  console.log(arg.length);
  return arg;
}
loggingIdentity(3);  // Error, number doesn't have a .length property
(6)Partial——将类型里的属性全变为可选项?
interface Todo {
  title: string;
  description: string;
}

function updateTodo(todo: Todo, fieldsToUpdate: Partial) {
  return { ...todo, ...fieldsToUpdate };
}

const todo1 = {
  title: "organize desk",
  description: "clear clutter",
};

const todo2 = updateTodo(todo1, {
  description: "throw out trash",
});

十三、装饰器

装饰器是一个表达式,入参是target、name和descriptor,返回一个函数,可能返回 descriptor 对象,用于配置 target 对象。它分为以下几类:

1、类装饰器

参数是 target:TFunction - 被装饰的类

function Greeter(target: Function): void {
  target.prototype.greet = function (): void {
    console.log("Hello Semlinker!");
  };
}
@Greeter
class Greeting {
  constructor() {
    // 内部实现
  }
}
let myGreeting = new Greeting();
myGreeting.greet(); // console output: 'Hello Semlinker!';

2、属性装饰器

装饰类的属性,两个参数:
· target: Object - 被装饰的类
· propertyKey: string | symbol - 被装饰类的属性名

3、方法装饰器

装饰类的方法,三个参数:
· target: Object - 被装饰的类
· propertyKey: string | symbol - 方法名
· descriptor: TypePropertyDescript - 属性描述符

4、参数装饰器

装饰函数参数,三个参数
· target: Object - 被装饰的类
· propertyKey: string | symbol - 方法名
· parameterIndex: number - 方法中参数的索引值

十四、编译上下文

1、tsconfig.json的作用

标识项目的根路径,配置编译器,指定编译的文件。

2、tsconfig.json的重要字段

· files - 设置要编译的文件的名称;
· include / exclude - 设置需要 / 不需 编译的文件,支持路径模式匹配;
· compilerOptions - 设置与编译流程相关的选项。

3、compilerOptions选项

baseUrl、 target、baseUrl、 moduleResolution 和 lib 等。具体看这里⏬:

 /* 基本选项 */
    "target": "es5",                       // 指定 ECMAScript 目标版本: 'ES3' (default), 'ES5', 'ES6'/'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'
    "module": "commonjs",                  // 指定使用模块: 'commonjs', 'amd', 'system', 'umd' or 'es2015'
    "lib": [],                             // 指定要包含在编译中的库文件
    "allowJs": true,                       // 允许编译 javascript 文件
    "checkJs": true,                       // 报告 javascript 文件中的错误
    "jsx": "preserve",                     // 指定 jsx 代码的生成: 'preserve', 'react-native', or 'react'
    "declaration": true,                   // 生成相应的 '.d.ts' 文件
    "sourceMap": true,                     // 生成相应的 '.map' 文件
    "outFile": "./",                       // 将输出文件合并为一个文件
    "outDir": "./",                        // 指定输出目录
    "rootDir": "./",                       // 用来控制输出目录结构 --outDir.
    "removeComments": true,                // 删除编译后的所有的注释
    "noEmit": true,                        // 不生成输出文件
    "importHelpers": true,                 // 从 tslib 导入辅助工具函数
    "isolatedModules": true,               // 将每个文件做为单独的模块 (与 'ts.transpileModule' 类似).

    /* 严格的类型检查选项 */
    "strict": true,                        // 启用所有严格类型检查选项
    "noImplicitAny": true,                 // 在表达式和声明上有隐含的 any类型时报错
    "strictNullChecks": true,              // 启用严格的 null 检查
    "noImplicitThis": true,                // 当 this 表达式值为 any 类型的时候,生成一个错误
    "alwaysStrict": true,                  // 以严格模式检查每个模块,并在每个文件里加入 'use strict'

    /* 额外的检查 */
    "noUnusedLocals": true,                // 有未使用的变量时,抛出错误
    "noUnusedParameters": true,            // 有未使用的参数时,抛出错误
    "noImplicitReturns": true,             // 并不是所有函数里的代码都有返回值时,抛出错误
    "noFallthroughCasesInSwitch": true,    // 报告 switch 语句的 fallthrough 错误。(即,不允许 switch 的 case 语句贯穿)

    /* 模块解析选项 */
    "moduleResolution": "node",            // 选择模块解析策略: 'node' (Node.js) or 'classic' (TypeScript pre-1.6)
    "baseUrl": "./",                       // 用于解析非相对模块名称的基目录
    "paths": {},                           // 模块名到基于 baseUrl 的路径映射的列表
    "rootDirs": [],                        // 根文件夹列表,其组合内容表示项目运行时的结构内容
    "typeRoots": [],                       // 包含类型声明的文件列表
    "types": [],                           // 需要包含的类型声明文件名列表
    "allowSyntheticDefaultImports": true,  // 允许从没有设置默认导出的模块中默认导入。

    /* Source Map Options */
    "sourceRoot": "./",                    // 指定调试器应该找到 TypeScript 文件而不是源文件的位置
    "mapRoot": "./",                       // 指定调试器应该找到映射文件而不是生成文件的位置
    "inlineSourceMap": true,               // 生成单个 soucemaps 文件,而不是将 sourcemaps 生成不同的文件
    "inlineSources": true,                 // 将代码与 sourcemaps 生成到一个文件中,要求同时设置了 --inlineSourceMap 或 --sourceMap 属性

    /* 其他选项 */
    "experimentalDecorators": true,        // 启用装饰器
    "emitDecoratorMetadata": true          // 为装饰器提供元数据的支持

喜欢作者,请关注公众号【CC前端手记】哦~

你可能感兴趣的:(TypeScript入门语法(下))