纵横研究院TS技术专题社区

TypeScript 基础知识入门 (一)

2019-12-01  本文已影响0人  Ange_057c

为什么会出现

下载安装

VSCode默认支持TypeScript

Sublime插件: https://github.com/Microsoft/TypeScript-Sublime-Plugin

全局安装

npm i -g typescript

手动编译

// 会在当前目录下生成一个编译后的js文件
tsc index.ts

自动编译(监测模式)

// 生成 tsconfig.json 文件(编译配置文件)
tsc init
tsc -p tsconfig.json -w

tsconfig.json 的编译选项

{
  "compilerOptions": {

    /* 基本选项 */
    "target": "es5",                       // 指定 ECMAScript 目标版本: 'ES3' (default), 'ES5', '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          // 为装饰器提供元数据的支持
  }
}

显式地指定需要编译的文件

{
  "files": [
    "./some/file.ts"
  ]
}

也可以指定包含的和排除的文件

{
  "include": [
    "./folder"
  ],
  "exclude": [
    "./folder/**/*.spec.ts",
    "./folder/someSubFolder"
  ]
}

基本类型

TypeScript 通过向 Js 增加可选的静态类型声明来把 Js变成强类型的程序语言。可选的静态类型声明可约束函数、变量、属性等。

TypeScript的类型检测在编译期进行并且没有运行时开销

number

// 浮点数,支持2、8、10、16进制
let height: number = 6;

boolean

let isDone: boolean = true;

string

// 可以使用字符串模板
let name: string = "jss";

array

// 由此类型元素组成的数据
let list: number[] = [1,2,3]

// 数组泛型
let list: Array<number> = [1,2,3]

tuple

元组:已知元素数量和类型的数组,类型可以不同

let x: [number, string];
x = [0, 'normal'];

x = [1, 'a'] // OK
x = ['a', 1] // error,类型不匹配
x = [1] // error,长度固定

// 在TypeScript2.7之后,元组的定义变成了有限制长度的数组,不能越界访问。
x[2] = ['官网']  // error

x.push(true) // error,不是(string | number)类型

// Ts 本质上还是 Js,就算声明约束为长度2的数组,依然可以push,但是 Ts 可以做的是限制继续在约束范围外进行其他操作
x.push('str') // 不会报错
console.log(x[2]) // error

enum

枚举:给一个数字集合(从0开始)更友好的命名

enum Color: { Red, Green, Blue };
let c: Color = Color.Green;  // 1

// 编译成ES5之后的代码
var Color;
(function (Color) {
    Color[Color["Red"] = 0] = "Red";
    Color[Color["Green"] = 5] = "Green";
    Color[Color["Blue"] = 6] = "Blue";
})(Color || (Color = {}));
var c = Color.Blue;

// 也可以使用自定义成员值
enum Status: { Success = 1, Err };
let s: Status = Status.Success; // 1
console.log(Status.Err); // 2 后面的名字映射的值也会改变
console.log(Status[1]); // Success 也可以通过枚举的值得到名字

any

可以表示一个不确定其类型的值,编译时可以对 any 类型的值最小化静态检查

let list: any[] = [1, 'a', true];

void

表示没有任何类型,当函数没有返回值时,返回值类型是void

function warnUser(): void {
    console.log("This is my warning message");
}

// 定义一个 void 类型的值只能赋值 undefined
let unusable: void = undefined;

undefined,null

let u: undefined;
console.log(u); // OK

let u: null;
console.log(u); // 编译不会报错,但有提示(赋值前使用了变量u)

let u: undefined = undefined;
let n: null = null;

never

表示永不存在的值的类型

// 总是会抛出异常的函数
function error(message: string): never {
    throw new Error(message);
}

// 不会有返回值的函数
function infiniteLoop(): never {
    while (true) {
    }
}

除了函数,变量也有可能是 never 类型,当它们为永不为真的类型保护约束时。

never 是任意类型的子类型,可以赋值给任何类型。

never 没有子类型,没有类型(包括 any)可以赋值给 never 类型,除了 never 本身

object

表示非原始类型

一个 Object.create API 的实现

declare function create(o: object | null): void;
create({ a: 1 }); // OK
create(null); // OK

联合类型

用来声明可以储存多种类型值的变更

let both: number[] | string
both = [1, 2, 3] // OK
both = 'a' // OK
both = 1 // error

变量声明

var, let, const --同 ES6

类型断言

可以明确自己定义的值的类型,不需要编译器进行特殊的数据检查和解构。

let foo: any;
let bar = <string>foo; // 现在 bar 的类型是 'string'

在 JSX 中使用这种“尖括号”的断言语法时,这会与 JSX 的语法存在歧义

let foo = <string>bar;</string>

所以另一种更好的语法是 as 语法

let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;

类型保护

可以在运行时使用 instanceof 和 typeof 运算符对类型进行验证

let x: any = { /* ... */ };
if( typeof x === 'string' ) {
    console.log(x.splice(3,1)); // Error,'string'上不存在'splice' 方法
}
// x 依然是 any 类型
x.foo(); // OK

TypeScript 在 if 中通过 typeof 运算符对 x 进行了类型检查,自动推断出 x 一定是 string 类型。

TypeScript 是可以理解 if 和 else 作用域的区别的,知道在其他块中的类型并不是 if 中的类型。

class Foo {
  foo = 123;
}
class Bar {
  bar = 123;
}

function doStuff(arg: Foo | Bar) {
  if (arg instanceof Foo) {
    console.log(arg.foo); // ok
    console.log(arg.bar); // Error
  } else {
    // 这个块中,一定是 'Bar'
    console.log(arg.foo); // Error
    console.log(arg.bar); // ok
  }
}

doStuff(new Foo());
doStuff(new Bar());

类型别名

允许使用 type 关键字声明类型别名

type PrimitiveArray = Array<string|number|boolean>
type MyNumber = number;
type Callback = () => void;

类型别名实质上与原来的类型一样,它们仅仅是一个替代的名字。类型别名可以让代码的可读性更高。

但是,如果在团队协作中,毫无约束地创建类型别名会导致可维护性的问题。

接口

为一些类型命名和为代码或第三方代码定义契约

简单示例

// 内联注解
declare const myPonit: { x: number; y: string };

// 接口定义,效果同上
interface Point {
    x: number;
    y: string;
}
declare const myPoint: Point;

使用接口的好处在于 TypeScript 接口是开放式的,可以用来模拟 JS 的可扩展性。

// a.ts
interface Point {
    x: number;
    y: string;
}
declare const myPoint: Point;

// b.ts
interface Point {
    z: boolean
}

// mt.ts
let myPoint.z

接口可以当做是一个名字,用来描述某种要求,如下,只要传入的对象有满足这个必要条件的,就是被允许的。

interface LabelledValue {
  label: string;
}

function printLabel(labelledObj: LabelledValue) {
  console.log(labelledObj.label);
}

let myObj = {size: 10, label: "Size 10 Object"};
printLabel(myObj);

可选属性

接口里的属性不全都是必需的

interface SquareConfig {
  color?: string;
  width?: number;
}

function createSquare(config: SquareConfig): {color: string; area: number} {
  let newSquare = {color: "white", area: 100};
  if (config.color) {
    newSquare.color = config.color;
  }
  if (config.width) {
    newSquare.area = config.width * config.width;
  }
  return newSquare;
}

let mySquare = createSquare({color: "black"});

通过属性名字后面添加 ? 可以把属性变成可选属性,好处是可以对可能存在的属性进行预定义,避免引用不存在属性。

只读属性

只能在对象创建的时候修改属性的值。

interface Point {
    readonly x: number;
    readonly y: number;
}
let p1: Point = { x: 10, y: 20 };
p1.x = 5; // error!

const 在定义一个对象的时候仍然可以对其属性进行编辑。

在 TypeScript 中也有只读数组的类型。

let a: number[] = [1, 2, 3, 4];
let ro: ReadonlyArray<number> = a;
ro[0] = 12; // error!
ro.push(5); // error!
ro.length = 100; // error!
let b: number[] = ro;  // error! 不能赋值给一个新数组

额外属性检查

interface LabelledValue {
  si?: number;
  label?: string;
}

function printLabel(labelledObj: LabelledValue) {
  console.log(labelledObj)
}
// 不会检查
let myObj = { size: 10, label: "Size 10 Object" }
printLabel(myObj);
// 会检查报错
printLabel({ size: 10, label: "Size 10 Object" });
上一篇 下一篇

猜你喜欢

热点阅读