TypeScript101

 

Create a new project

$ npm init -y                    # 初始化 npm
$ npm install --save-dev typescript      # 安裝 typescript
$ npx tsc --init             # 產生 TS 設定檔 tsconfig.json
$ npx ts-node index.ts

# 將 TS 編譯成 JS
$ tsc # Run a compile based on a backwards look through the fs for a tsconfig.json
$ tsc index.ts
$ tsc src/*.ts # Transpile any .ts files in the folder src, with the default settings
$ tsc --watch  # 常駐使用語法檢測
  • ts-node-dev:當檔案有變更時能夠自動重啟(不是自動重新打包)
  • ts-node:不需重新打包就可以直接執行 ts 檔

如果想更加了解tsconfig可以看

https://www.digitalocean.com/community/tutorials/typescript-new-project

配置nodemon + ts-node/ 單獨使用ts-node-dev來協助開發

最簡便的方式是直接使用tsc --watch xxx.ts來追蹤更改的code

nodemon + ts-node

https://pjchender.dev/typescript/guide-getting-started/#%E9%80%8F%E9%81%8E-nodemon-%E6%90%AD%E9%85%8D-ts-node-%E8%87%AA%E5%8B%95-reload-%E8%88%87%E7%B7%A8%E8%AD%AF

ts-node-dev

https://dev.to/husnaram/hot-reload-typescript-with-ts-node-dev-75i

只需要在package.json中做簡單的一行設定

"scripts": {
    ...
    "dev": "ts-node-dev --respawn src/index.ts"
}

如果要搭配code-runner插件需要額外設定

配置settings.json

上圖中的tsc要改成ts-node-dev

在vscode中debug也需要額外設定

https://stackoverflow.com/questions/61190639/how-to-debug-typescript-code-in-visual-studio-code-with-ts-node-dev-and-correct

語法

自動推論型態

val id: number = 10;
id = '10';

就算語法有錯依然可以轉(編譯)成js檔

tuple vs array

Typically, a tuple is ==an array with fixed size== and known datatypes. tuple stores data in an unchanging array

const primaryColors: [string, string, string] = ['#ff0000', '#00ff00', '#0000ff'];
console.log(primaryColors);

array混用 type

const nameAge: (string | number)[] = ['Osinachi', 10011, 12345, "Victor"];
console.log(nameAge);

tuple可以混type

const nameAge: [string, number] = ['Osinachi', 10011];
console.log(nameAge);

enum

如果是number會自動遞增

enum Sequence1 {
    first,
    second,
    third
}

console.log(Sequence1.first);
console.log(Sequence1.second);

會印出0與1

enum Sequence1 {
    first=2,
    second,
    third
}

console.log(Sequence1.first);
console.log(Sequence1.second);

後面的值會是第一個開始的遞增, 所以會印出2與3

相較object的好處, 不會直接被修改成其他值

const enum FieldNamesEnum {
  FirstField = "Field One",
  SecondField = "Field Two"
};

let x: FieldNamesEnum;

x = FieldNamesEnum.FirstField;
x = FieldNamesEnum.SecondField;

// Error - not assignable to FieldNames
x = 'str';

// Cannot assign
FieldNamesEnum.FirstField = 'str';

https://stackoverflow.com/questions/47351323/what-is-the-difference-between-enum-and-object-in-typescript


Ref:

  • Settings:
    • https://pjchender.dev/typescript/guide-getting-started/
  • Crash course:
    • https://www.youtube.com/watch?v=BCg4U1FzODs
  • Tuple:
    • https://www.educative.io/edpresso/arrays-vs-tuples-in-typescript
    • https://dev.to/spukas/typescript-arrays-and-tuples-j58