Types in TypeScript

 TypeScript有Primitive Types 跟 Object Type


Primitive Types : number, boolean, string, null, void, undefined, symbol

Object Types: functions, classes, array, object


First App in TypeScript

打開cmd

輸入 mkdir fetchJson (意思是創建一個叫fetchJson的資料夾)

然後輸入 cd fetchJson(進入這個資料夾)

輸入  npm init -y  (產生package.json檔)

輸入  npm install axios (安裝axios套件)

最後輸入 code . 就可以直接開啟載入這個資料夾的vscode

在資料夾內新增一個index.ts

然後輸入以下code

import axios from "axios";

const url = "https://jsonplaceholder.typicode.com/todos/1"

axios.get(url).then(response => {
  console.log(response.data)
})

之後在cmd輸入 tsc index.ts 去編譯這個ts檔

結束後會看到資料夾內多了一個index.js  這就是剛剛的index.ts編譯出來的js檔

在cmd輸入 node index.js

就可以得到以下資料




或是輸入ts-node index.ts 也可以




之後將程式修改如下 再執行一次ts-node index.ts 

import axios from "axios";

const url = "https://jsonplaceholder.typicode.com/todos/1"

axios.get(url).then(response => {
  const todo = response.data;
  const ID = todo.id
  const title = todo.title
  const finished = todo.completed

  console.log(`
  ID = ${ID}
  title = ${title}
  finished = ${finished}
  `)
})



最後再修改程式碼如下
定義一個Todo介面

import axios from "axios";

const url = "https://jsonplaceholder.typicode.com/todos/1"

interface Todo{
  id:number;
  title:string;
  completed: boolean
}

axios.get(url).then(response => {
  const todo = response.data as Todo;
  const ID = todo.id
  const title = todo.title
  const finished = todo.completed

  console.log(`
  ID = ${ID}
  title = ${title}
  finished = ${finished}
  `)
})


把console.log功能拆出來 會發現下面有紅線 代表錯誤












原因是跟傳入的參數名稱不一致  修正就好了

這也是typescript的好處  在開發時就會檢查錯誤



Typescript簡介

What is typescript?
Typescript = Javascript + Type system


TypeScript vs JavaScript:

Advantage of TypeScript over JavaScript  

  • TypeScript always highlights errors at compilation time during the time of development, whereas JavaScript points out errors at the runtime.
  • TypeScript supports strongly typed or static typing, whereas this is not in JavaScript.
  • TypeScript runs on any browser or JavaScript engine.
  • Great tooling supports with IntelliSense, which provides active hints as the code is added.
  • It has a namespace concept by defining a module.

Disadvantage of TypeScript over JavaScript

  • TypeScript takes a long time to compile the code.
  • TypeScript does not support abstract classes.
  • If we run the TypeScript application in the browser, a compilation step is required to transform TypeScript into JavaScript.