TypeScript入門一:最簡(jiǎn)單的命令行程序

開始

新建文件1.ts

#!/usr/bin/env ts-node     //此為shebang,說明該腳本用什么語言解析,并利用env查找該在哪查找該語言 
console.log('hello world')

然后給該文件添加執(zhí)行權(quán)限:chmod +x ./1.ts (Windows 用戶不需要做這個(gè),直接在 Git Bash 輸入 ./1.ts 即可運(yùn)行)

執(zhí)行 ./1.ts

就會(huì)看到 hello world

接受命令行參數(shù)

1.ts

#!/usr/bin/env ts-node
console.log(process.argv)  

如果沒有配置好 TS,那么運(yùn)行 ./1.ts 上面代碼會(huì)出現(xiàn)如下報(bào)錯(cuò):

/usr/local/lib/node_modules/ts-node/src/index.ts:261
    return new TSError(diagnosticText, diagnosticCodes)
           ^
TSError: ? Unable to compile TypeScript:
2.ts(2,13): error TS2304: Cannot find name 'process'.

    at createTSError (/usr/local/lib/node_modules/ts-node/src/index.ts:261:12)
    at getOutput (/usr/local/lib/node_modules/ts-node/src/index.ts:367:40)
    at Object.compile (/usr/local/lib/node_modules/ts-node/src/index.ts:557:11)
    at Module.m._compile (/usr/local/lib/node_modules/ts-node/src/index.ts:439:43)
    at Module._extensions..js (module.js:663:10)
    at Object.require.extensions.(anonymous function) [as .ts] (/usr/local/lib/node_modules/ts-node/src/index.ts:442:12)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Function.Module.runMain (module.js:693:10)

報(bào)錯(cuò)說得很清楚,2.ts(2,13): error TS2304: Cannot find name 'process'. 找不到 process。

實(shí)際上這是 Node.js 的全局變量,不可能找不到。

這就是 TS 的厲害之處:如果你不告訴我 process 是什么,我就不允許你用 process。

那么如何告訴 TS process 是什么呢?

方法如下:

# 初始化項(xiàng)目的 package.json
> npm init -y
# 安裝 node 相關(guān)的類型定義
> npm install @types/node
# 再次運(yùn)行 ./1.ts
> ./1.ts
[ 'node', '/Users/frank/TypeScript/tsdemo/1.ts' ]

就可以了。

那么 @types/node 到底定義了什么呢?打開 ./node_modules/@types/node/index.d.ts 搜索 Process 就能看到 process 的定義了:

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

另一個(gè)很懸疑的問題:你怎么知道要運(yùn)行 npm install @types/node

對(duì)啊,我怎么知道。新人根本不可能知道啊。

過程:

  1. 復(fù)制 error TS2304: Cannot find name 'process'. 到 Google
  2. 找到 Stackoverflow 上的一篇問答
  3. 得知要安裝 Typings,于是點(diǎn)開他給的鏈接
  4. 看到頁面上方顯示 Typings is deprecated in favor of NPM @types
  5. 得知 Typings 已經(jīng)被棄用了,但是這貨不告訴我新版在哪
  6. 猜測(cè)新版是 @types/node (純經(jīng)驗(yàn))
  7. 運(yùn)行 npm install @types/node 然后運(yùn)行 ./2.ts 發(fā)現(xiàn)成功
  8. 去 Stackoverflow 回復(fù)一下,以防別人也遇到不知道新版名稱
  9. 回復(fù)的時(shí)候發(fā)現(xiàn)已經(jīng)有人回復(fù)了 with typescript 2, its now npm i -D @types/node
  10. 發(fā)現(xiàn)他用了 -D 選項(xiàng)但是我沒有使用,根據(jù)我對(duì) npm 的了解,加不加 -D 都行,加上更好一點(diǎn)。

寫一個(gè)簡(jiǎn)單計(jì)算器

由于TS中,process.argv返回規(guī)定為字符串,故接收參數(shù)是需要轉(zhuǎn)型。

image.png

添加ts配置

使支持es6語法。

image.png
{
    "compilerOptions": {
        "lib":[
            "es2015",
            "es2016",
            "es2017",
            "es2018",
            "dom",
            "es5"
        ]

    },
}
#!/usr/bin/env ts-node
{
    const a = process.argv[2];
    let b: [number, number]   //限制內(nèi)容類型的元組
    let arr:number[] = []
    if(a.match(/\+/)){
        parseIntStr(a.split('+'))
        add(b)
    }else if(a.match(/\-/)){
        parseIntStr(a.split('-'))
        minus(b)
    }else if(a.match(/\*/)){
        parseIntStr(a.split('*'))
        multiply(b)
    }else if(a.match(/\//)){
        parseIntStr(a.split('/'))
        devide(b)
    }

    function parseIntStr(c):void{    //void為不返回內(nèi)容
        const x: number = parseInt(c[0]);
        const y: number = parseInt(c[1]);
        b=[x,y]      //元組賦值
    }

    function rules(a):void{
        if (Number.isNaN(a[0]) || Number.isNaN(a[1])) {    //es6語法,需要配置tsconfig方可使用
            console.log('輸入不合法');
            process.exit(2);        //停止進(jìn)程
        }
    }


    function add(a):void{
        rules(a)
        console.log(a[0] + a[1]);
        process.exit(0);
    }

    function minus(a):void{
        rules(a)
        console.log(a[0] - a[1]);
        process.exit(0);
    }

    function multiply(a):void{
        rules(a)
        console.log(a[0] * a[1]);
        process.exit(0);
    }

    function devide(a):void{
        rules(a)
        if(a[1] === 0){
            console.log('被除數(shù)不能為0')
            process.exit(3);
        }
        console.log(a[0] / a[1]);
        process.exit(0);
    }

    console.log('請(qǐng)正確輸入式子')
    process.exit(0);

}

寫一個(gè)族譜(樹)

#!/usr/bin/env ts-node
function createTabs(n: number): string {
  return '----'.repeat(n);
}
class Person {
  public children: Person[] = [];
  constructor(public name) {}
  addChild(child: Person): void {
    this.children.push(child);
  }
  introduceFamily(n?: number): void {      //問號(hào)為不確定參數(shù),可傳可不傳
    n = n || 0;
    console.log(`${createTabs(n)}${this.name}`);
    this.children.forEach(person => {
      person.introduceFamily(n + 1);
    });
  }
}

const grandPa = new Person('王麻子');
const person1 = new Person('王大錘');
const person2 = new Person('王者');
const child11 = new Person('王毛');
const child12 = new Person('王水');
const child21 = new Person('王榮耀');
const child22 = new Person('王農(nóng)藥');

grandPa.addChild(person1);
grandPa.addChild(person2);

person1.addChild(child11);
person1.addChild(child12);
person2.addChild(child21);
person2.addChild(child22);

grandPa.introduceFamily();

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容