Typescript # 1 configuration with the simple command line program

Vue3.0 bottom should use ts rewrite, I believe the future can use javascript to write have written with typescript

Prerequisites

node installation is not to say that this must have.

Taobao source configuration, installation or NRM, to facilitate handover source npm version (the latter recommended)

npm config set registry https://registry.npm.taobao.org/

installation

npm install [email protected] -g
npm install [email protected] -g // 让node支持ts

Profiles

In a terminal tsc --init: it is a TypeScript project profile may be set by reading it TypeScript compiler compiler flags

{
  "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          // 为装饰器提供元数据的支持
  }
}

You can also specify files not to be compiled

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

Files can include and exclude options to specify the file needs included and excluded

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

Simple command line program

skill

File write the first line #!/usr/bin/env ts-nodeof action?

  • This is the shebang, explain what the script language parsing, and using the env look at where to find the language

Add execute permissions to the file

// 添加可执行权限(windows用户不需要)
chmod +x 1.ts
// 添加执行权限后可以直接执行文件,如下
./1.ts

In this way, we can print process.argv by giving cmd.ts file, to get to the command line parameters!

┌─(~/TypeScript/tsdemo)────────────────────────────────────────────(gaohang@isaacgao:s005)─┐ ────────────────────────────────────────(gaohang@isaacgao:s005)─┐
└─(22:59:03)──> ./cmd.ts haha xixi                                           ──(Sun,Jun30)─┘                                                   ──(Sat,Jun29)─┘
hello world                                                                                  'string'.
[ 'node',
  '/Users/gaohang/TypeScript/tsdemo/cmd.ts',
  'haha',
  'xixi' ]
┌─(~/TypeScript/tsdemo)────────────────────────────────────────────(gaohang@isaacgao:s005)─┐ ────────────────────────────────────────(gaohang@isaacgao:s005)─┐
└─(23:05:23)──>     

New add.ts, execution

#!/usr/bin/env ts-nod
let a: number = process.argv[2];
let b: number = process.argv[3];
console.log(a + b);

//执行 ./add.ts 1 2

As we execute ./add.ts 1 2obtained after 12, is not expected in the 3. One can imagine, a where, b is the sum of the string type. When we use the typescript to a, b regulate the type of number, vscode immediately underlined in red:[ts] Type 'string' is not assignable to type 'number'.

This is powerful place typescript of the code is running on a non-type errors let us know!

Further, VSCode provides a convenient, while the cursor points to hold the cmd process.argvcan locate the global process index.d.ts source

interface Process extends EventEmitter {
        stdout: WriteStream;
        stderr: WriteStream;
        stdin: ReadStream;
        openStdin(): Socket;
        argv: string[];
        argv0: string;
        execArgv: string[];
        execPath: string;
        abort(): void;
        ......

Noticed above, argv is an array of type String, which explains why the above process.argv[2]returns a string, and specifications for the number or after the error.

We continue to look at the following iteration add.ts

#!/usr/bin/env ts-node
let a: number = parseInt(process.argv[2]);
let b: number = parseInt(process.argv[3]);

if (Number.isNaN(a) || Number.isNaN(b)) {
  console.warn('对不起哦,你的输入错误了');
  process.exit(0)
}

console.log(a + b);

Note that the following is not performed, the process can be used to exit process.exit(0)the general procedure agreed, exit (0) is the normal exit (ie returns 0), the remaining data is abnormal exit, a different number may correspond to different types of errors.

After performing even being given, the removal of key information is as follows:

TSError: ⨯ Unable to compile TypeScript:
add.ts(5,12): error TS2339: Property 'isNaN' does not exist on type 'NumberConstructor'.
add.ts(5,31): error TS2339: Property 'isNaN' does not exist on type 'NumberConstructor'.

By Google, you will find that the problem is to use the current version does not support api in ts in! The solution is to create a new profile in the root directory tsconfig.json

{
  "compilerOptions": {
    "lib": [
      "es2015"
    ]
  }
}

skill

Function has no return value can be explicitly specified: void{}

⚠️ optional parameters : parameters behind a question mark,function xxx(n? :number): void {......}

If you think the code is a mess and need to be optimized to use extraction function method, the function extracts as a function.

if (!n) {
    n = 1
}
// 优化为
n = n || 1

interface: the interface declaration must be in full compliance with the wording of the interface, it does not complain, can be more, but no less!

public: class written inside public + parameter represents the student has three properties, the equivalent of the variable declaration and assignment (this.name = name) to streamline;

Function: parameters and return values ​​are predetermined type

Genealogy command line program

The following basic use typescript be further understood through a simple type of line printing command genealogy program.

function createTabs(n: number): string {
  return '----'.repeat(n);
}

class Person {
  public children: Person[] = []
  constructor(public name: string) {}
  addChild(child: Person): void {
    this.children.push(child)
  }
  introduceFamily(n?: number): void {
    n = n || 0;
    // 打印族谱
    console.log(`${createTabs(n)}${this.name}`)
    this.children.forEach((child) => {
      child.introduceFamily(n + 1)
    })
  }
}

const grandFather = new Person('王爷爷')
const child1 = new Person('王爸爸')
const child2 = new Person('王舅舅')
const child11 = new Person('王爸爸大儿子')
const child12 = new Person('王爸爸二儿子')
const child21 = new Person('王舅舅大儿子')
const child22 = new Person('王舅舅二儿子')
const child23 = new Person('王舅舅三儿子')
const child221 = new Person('王舅舅二儿子的女儿')

grandFather.addChild(child1)
grandFather.addChild(child2)
child2.addChild(child21)
child2.addChild(child22)
child2.addChild(child23)
child1.addChild(child11)
child1.addChild(child12)
child22.addChild(child221)

grandFather.introduceFamily()

// 返回如下
王爷爷
----王爸爸
--------王爸爸大儿子
--------王爸爸二儿子
----王舅舅
--------王舅舅大儿子
--------王舅舅二儿子
------------王舅舅二儿子的女儿
--------王舅舅三儿子

Guess you like

Origin www.cnblogs.com/CharmanderS5/p/11119868.html