中文代碼示例之5分鐘入門TypeScript

"中文編程"知乎專欄原文html

Typescript官方文檔起的這個噱頭名字: TypeScript in 5 minutes, 雖然光看完文章就不止5分鐘...走完整個文檔流水帳以下(代碼編輯器用的是VS Code)git

源碼在: program-in-chinese/typescript_in_5_min_zh 第一個TypeScript程序github

function 問好(那誰) {
  return "吃了麼, " + 那誰;
}

let 路人 = "打醬油的";

document.body.innerHTML = 問好(路人);

運行typescript

tsc 問好.ts

編譯生成"問好.js"文件. 添加參數類型編程

function 問好(那誰: string) {
   return "吃了麼, " + 那誰;
}

若是'那誰'的類型不符, 好比是數組類型[0,1,2], 編譯時會報錯, 挺好:數組

問好.ts(7,30): error TS2345: Argument of type 'number[]' is not assignable to parameter of type 'string'.

添加接口瀏覽器

interface 人 {
  姓: string;
  名: string;
}

function 問好(那誰: 人) {
  return "吃了麼, " + 那誰.姓 + 那誰.名;
}

let 路人 = {姓: "大", 名: "黃"};

這裏路人的"形狀"符合"人", 類型就被斷定爲相符.網絡

本身誤寫成了:編輯器

function 問好(那誰: 人) {
  return "吃了麼, " + 人.姓 + 人.名;
}

編譯提示'人'是個類型而不是值, 挺好:ide

問好.ts(7,20): error TS2693: '人' only refers to a type, but is being used as a value here.

添加類

class 學生 {
  全名: string;
  constructor(public 姓: string, public 名: string) {
    this.全名 = 姓 + 名;
  }
}

interface 人 {
  姓: string;
  名: string;
}

function 問好(那誰: 人) {
  return "吃了麼, " + 那誰.姓 + 那誰.名;
}

let 路人 = new 學生("大", "黃");

官方文檔說添加class以後編譯生成的js文件與沒有class的相同, 這裏不解, 實驗結果是不一樣的. 運行第一個網絡應用

爲了檢驗js文件, 添加HTML文件:

<!DOCTYPE html>
<html>
    <head><title>TypeScript你好</title></head>
    <body>
        <script src="問好.js"></script>
    </body>
</html>

最後一個插曲:

html文件在Chrome中打開顯示正確:

吃了麼, 大黃

但在火狐(Firefox)瀏覽器中打開時報錯:

The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must be declared in the document or in the transfer protocol.
%E9%97%AE%E5%A5%BD.html

將View->TextEncoding從Western改成Unicode後顯示正確.

後感:

tsc編譯好慢!

TypeScript代碼看起來更好理解一點, 編譯期的反饋信息對於減小錯誤頗有用.

原文出處:https://www.cnblogs.com/program-in-chinese/p/typescript-in-5-minutes-with-sample-code-in-Chinese.html

相關文章
相關標籤/搜索