• 【One by one系列】一步步学习TypeScript


    TypeScript Quick Start

    1.TypeScript是什么?

    • TypeScript是ES6的超集。

    • TS>ES7>ES6>ES5

    • Vue3.0已经宣布要支持ts,至于以前为啥没用呢,尤雨溪:“至于当初为什么没用 TS,我之前的回答相信很多人都看过了,谁能想到 Flow 团队会这么烂尾呢。相比之下,TS 团队确实是在用心做事的。Daniel Rosenwasser (TS 的 PM)跟我沟通过很多次,还来参加过 VueConf,都变成熟人了,不用都不好意思...Vue 2 一开始内部实现就有类型系统,但是没想到 Flow 烂尾了,而 TS 整个生态越做越好。这个属于就是押错宝了,只能说... 真香”

    • angular就不说了,从2开始,就绑着ts用

    • node能用js写后端,ts能编译成es,推导=>ts也能写后端(文章末尾,就是ts用express写web)

    • 优势:

      • TypeScript 增加了静态类型、类、模块、接口和类型注解,编译阶段就能检查错误
      • TypeScript 可用于开发大型的应用,也是由于上面的优势点,所以才有此优势,项目一大就需要考虑可维护性

    想弯道超车吗!?快速追上前端潮流吗!?那么开始使用ts或许是个选择,当然这有一点急功近利,不提倡。

    2.安装

    npm install -g typescript

    3.编译

    .ts文件编译成JavaScript

    tsc greeter.ts

    4.类型注解

    function greeter(persion:string){
    	return "Hello, "+persion
    }
    let user=[0,1,2];
    greeter(user);//编译错误
    

    5.接口

    duck-type programming

    //允许我们在实现接口时候只要保证包含了接口要求的结构就可以,而不必明确地使用 implements语句。
    interface Person{
        firstName:string;
        lastName:string;
    }
    
    function greeter(person: Person) {
        return "Hello, " + person.firstName + " " + person.lastName;
    }
    
    let user = { firstName: "Jane", lastName: "User" };
    greeter(user);
    
    

    6.类

    在构造函数的参数上使用public等同于创建了同名的成员变量。

    class Student {
        fullName: string;
        constructor(public firstName, public middleInitial, public lastName) {
            this.fullName = firstName + " " + middleInitial + " " + lastName;
        }
    }
    
    interface Person {
        firstName: string;
        lastName: string;
    }
    
    function greeter(person : Person) {
        return "Hello, " + person.firstName + " " + person.lastName;
    }
    
    let user = new Student("Jane", "M.", "User");
    
    greeter(user);
    

    7.类型定义文件(*.d.ts)

    类型定义文件用来帮助开发者在TypeScript中使用已有的JavaScript包

    通俗一点,这个文件就是一个typescript的模块,把需要使用的JavaScript包里面的内容,以typescript类或者模块的方式暴露出来,然后供你import

    //a.ts
    function hide(){
    	$('#content').hide();//报错
    }
    //这里ts会报错,TypeScript不知道$是什么,换句话说,Ts不认识美元符号,所以需要有一个文件来告诉typescript,$是要调用jquery,---这个文件就是类型定义文件
    

    8.tsconfig.json

    8.1.概述

    tsconfig.json文件存在的目录,即为TypeScript项目的根目录

    tsconfig.json文件中指定了用来编译项目的根文件和编译参数选项。

    8.2.编译规则

    使用tsconfig.json

    • 不带任何输入文件,tsc,编译器会从当前目录开始去查找tsconfig.json文件,逐级向上搜索父目录。
    • 不带任何输入文件,tsc,且使用命令行参数 --project(或p)指定一个包含tsconfig.json文件的目录。tsc --project var/sss/test
    • 当命令行上指定了输入文件时,tsconfig.json文件会被忽略

    8.3.tsconfig.json

    {
        "compilerOptions": {
            "module": "system",//指定生成哪个模块系统代码: "None", "CommonJS", "AMD", "System", "UMD", "ES6"或 "ES2015"。【ps】只有 "AMD"和 "System"能和 --outFile一起使用。【ps】"ES6"和 "ES2015"可使用在目标输出为 "ES5"或更低的情况下。
            "noImplicitAny": true,//在表达式和声明上有隐含的 any类型时报错。
            "removeComments": true,//删除所有注释,除了以 /!*开头的版权信息。
            "preserveConstEnums": true,//保留 const和 enum声明。
            "outFile": "../../built/local/tsc.js",//将输出文件合并为一个文件。合并的顺序是根据传入编译器的文件顺序和 ///<reference``>和 import的文件顺序决定的。查看输出文件顺序文件了解详情。
            "sourceMap": true//生成相应的 .map文件。
        },
        "files": [
            "core.ts",
            "sys.ts",
            "types.ts",
            "scanner.ts",
            "parser.ts",
            "utilities.ts",
            "binder.ts",
            "checker.ts",
            "emitter.ts",
            "program.ts",
            "commandLineParser.ts",
            "tsc.ts",
            "diagnosticInformationMap.generated.ts"
        ],//项目中不需要
        "include": [
            "src/**/*"
        ],
        "exclude": [
            "node_modules",
            "**/*.spec.ts"
        ]
    }
    
    • "compilerOptions"可以被忽略,这时编译器会使用默认值。在这里查看完整的编译器选项列表。
    • "files"指定一个包含相对或绝对文件路径的列表。 "include""exclude"属性指定一个文件glob匹配模式列表。
    • 使用 "outDir"指定的目录下的文件永远会被编译器排除,除非你明确地使用"files"将其包含进来(这时就算用exclude指定也没用)。
    • 使用"include"引入的文件可以使用"exclude"属性过滤。 然而,通过 "files"属性明确指定的文件却总是会被包含在内,不管"exclude"如何设置。 如果没有特殊指定, "exclude"默认情况下会排除node_modulesbower_componentsjspm_packages和``目录。
    • tsconfig.json文件可以是个空文件,那么所有默认的文件都会以默认配置选项编译。

    9.one by one实战改造express代码

    9.1初始化tsconfig.json

    tsc --init

    9.2修改tsconfig.json文件

    {
      "compilerOptions": {
        /* Basic Options */
        // "incremental": true,                   /* Enable incremental compilation */
        "target": "es6",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
        "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
        // "lib": [],                             /* Specify library files to be included in the compilation. */
        // "allowJs": true,                       /* Allow javascript files to be compiled. */
        // "checkJs": true,                       /* Report errors in .js files. */
        // "jsx": "preserve",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
        // "declaration": true,                   /* Generates corresponding '.d.ts' file. */
        // "declarationMap": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */
        // "sourceMap": true,                     /* Generates corresponding '.map' file. */
        // "outFile": "./",                       /* Concatenate and emit output to single file. */
         "outDir": "./dist",                        /* Redirect output structure to the directory. */
         "rootDir": "./src",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
        // "composite": true,                     /* Enable project compilation */
        // "tsBuildInfoFile": "./",               /* Specify file to store incremental compilation information */
        // "removeComments": true,                /* Do not emit comments to output. */
        // "noEmit": true,                        /* Do not emit outputs. */
        // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
        // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
        // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
    
        /* Strict Type-Checking Options */
        "strict": true,                           /* Enable all strict type-checking options. */
        // "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */
        // "strictNullChecks": true,              /* Enable strict null checks. */
        // "strictFunctionTypes": true,           /* Enable strict checking of function types. */
        // "strictBindCallApply": true,           /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
        // "strictPropertyInitialization": true,  /* Enable strict checking of property initialization in classes. */
        // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
        // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */
    
        /* Additional Checks */
        // "noUnusedLocals": true,                /* Report errors on unused locals. */
        // "noUnusedParameters": true,            /* Report errors on unused parameters. */
        // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
        // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */
    
        /* Module Resolution Options */
        "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
        // "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
        // "paths": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
        // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
        // "typeRoots": [],                       /* List of folders to include type definitions from. */
        // "types": [],                           /* Type declaration files to be included in compilation. */
        // "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
        "esModuleInterop": true,                  /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
        // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */
        // "allowUmdGlobalAccess": true,          /* Allow accessing UMD globals from modules. */
    
        /* Source Map Options */
        // "sourceRoot": "",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */
        // "mapRoot": "",                         /* Specify the location where debugger should locate map files instead of generated locations. */
        // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
        // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
    
        /* Experimental Options */
        // "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
        // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */
    
        /* Advanced Options */
        "forceConsistentCasingInFileNames": true  /* Disallow inconsistently-cased references to the same file. */
      }
    }
    
    

    9.3新建src

    mkdir src

    9.4安装express、nodemon、ts-node及类型定义文件

    npm init -y

    cnpm i express

    cnpm i -D typescript ts-node nodemon @types/node @types/express

    nodemon这个工具,它的作用是监听代码文件的变动,当代码改变之后,自动重启。

    ts-nodeTypeScript execution environment and REPL for node.简单的说就是它提供了TypeScript的运行环境,让我们免去了麻烦的编译这一步骤。

    9.5修改package.json

    {
      "name": "ts-demo",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "start": "node dist/index.js", //启动服务
        "dev":"nodemon src/index.ts",//监听文件变化 
        "build":"tsc -p ."//编译文件
      },//主要修改在这里
      "keywords": [],
      "author": "",
      "license": "ISC",
      "dependencies": {
        "jquery": "^3.4.1"
      },
      "devDependencies": {
        "@types/express": "^4.17.2",
        "@types/node": "^13.7.6",
        "nodemon": "^2.0.2",
        "ts-node": "^8.6.2",
        "typescript": "^3.8.2"
      }
    }
    
    

    9.6编码

    //es6写法
    // import express from "express";
    
    // const app= express();
    
    // app.get('/',(req,res)=>{
    //     res.send("hello,I'm Carfield")
    // })
    // app.listen(5000,()=>{
    //     console.log('Server running,port:5000...');
    // })
    
    
    //ts写法,明显的类型注解,改改参数 感受下ts带来的好处
    import express,{Application,Request,Response,NextFunction  } from "express";
    
    
    const add=(a:number,b:number):number=>a+b
    
    const app:Application=express();
    app.get('/',(req:Request,res:Response,next:NextFunction)=>{
        console.log(add(5,5));   
        res.send("hello,I'm Carfield")
    })
    app.listen(5000,()=>{
        console.log('Server running,port:5000...');
    })
    

    9.7开发调试

    npm run dev

    试试看,修改下add(5,'5')

    ....
    TSError: ⨯ Unable to compile TypeScript:
    src/index.ts:22:23 - error TS2345: Argument of type '"5"' is not assignable to parameter of type 'number'.
    
    22     console.log(add(5,'5'));
    

    9.8编译

    npm run build

    9.9启动

    npm start

    `

    Server running,port:5000...
    
  • 相关阅读:
    结构化分析工具之判定树
    结构化分析工具之判定表
    结构化分析工具之结构化语言
    结构化分析工具之数据字典
    结构化分析工具之数据流图
    结构化分析方法
    软件生存周期模型之V模型
    软件生存周期模型之喷泉模型
    软件生存周期模型之螺旋模型
    软件生存周期模型之原型模型
  • 原文地址:https://www.cnblogs.com/RandyField/p/12375561.html
Copyright © 2020-2023  润新知