1. 程式人生 > 實用技巧 >【TypeScript】01 基礎入門

【TypeScript】01 基礎入門

前提:使用TypeScript你需要安裝NodeJS支援

然後安裝TypeScript:

npm intsall -g typescript

安裝完成後檢視版本號:

tsc -v

新建一個TypeScript檔案(hello-typescript.ts):

let message:string = "Hello TypeScript!!!";
console.log(message);

對這個ts檔案編譯:

tsc hello-typescript.ts

編譯之後會生成一個javascript檔案:

再由NodeJS執行這個js檔案

node hello-typescript.js

執行結果:

C:\Users\User-Dai\IdeaProjects\Type-Script\ts-01>node ts-test-01.js
Hello TypeScript!!!

其實tsc就是:TypeScript-Compiler

【tsc 常用編譯引數】

檢視幫助資訊:

C:\Users\User-Dai\IdeaProjects\Type-Script\ts-01>tsc --help
Version 3.9.7
Syntax:   tsc [options] [file...]

Examples: tsc hello.ts
          tsc --outFile file
.js file.ts tsc @args.txt tsc --build tsconfig.json Options: -h, --help Print this message. -w, --watch Watch input files. --pretty Stylize errors and messages using color and context (experimental).
--all Show all compiler options. -v, --version Print the compiler's version. --init Initializes a TypeScript project and creates a tsconfig.json file. -p FILE OR DIRECTORY, --project FILE OR DIRECTORY Compile the project given the path to its configuration file, or to a folder with a 'tsconfig.json'. -b, --build Build one or more projects and their dependencies, if out of date -t VERSION, --target VERSION Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. -m KIND, --module KIND Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. --lib Specify library files to be included in the compilation. 'es5' 'es6' 'es2015' 'es7' 'es2016' 'es2017' 'es2018' 'es2019' 'es2020' 'esnext' 'dom' 'dom.iterable' 'webworker' 'webworker.importscripts' 'scripthost' 'es2015.core' 'es2015.collection' 'es2015.generator' 'es2015.iterable' 'es2015.promise' 'es2015.proxy' 'es2015.reflect' 'es2015.symbol' 'es2015.symbol.wellknown' 'es2016.array.include' 'es2017.object' 'es2017.sharedmemory' 'es2017.string' 'es2017.intl' 'es2017.typedarrays' 'es2018.asyncgenerator' 'es2018.asynciterable' 'es2018.intl' 'es2018.promise' 'es2018.regexp' 'es2019.array' 'es2019.object' 'es2019.stri ng' 'es2019.symbol' 'es2020.bigint' 'es2020.promise' 'es2020.string' 'es2020.symbol.wellknown' 'esnext.array' 'esnext.symbol' 'esnext.asynciterable' 'esnext.intl' 'esnext.bigint' 'esnext.string' 'esnext.promise' --allowJs Allow javascript files to be compiled. --jsx KIND Specify JSX code generation: 'preserve', 'react-native', or 'react'. -d, --declaration Generates corresponding '.d.ts' file. --declarationMap Generates a sourcemap for each corresponding '.d.ts' file. --sourceMap Generates corresponding '.map' file. --outFile FILE Concatenate and emit output to single file. --outDir DIRECTORY Redirect output structure to the directory. --removeComments Do not emit comments to output. --noEmit Do not emit outputs. --strict Enable all strict type-checking options. --noImplicitAny Raise error on expressions and declarations with an implied 'any' type. --strictNullChecks Enable strict null checks. --strictFunctionTypes Enable strict checking of function types. --strictBindCallApply Enable strict 'bind', 'call', and 'apply' methods on functions. --strictPropertyInitialization Enable strict checking of property initialization in classes. --noImplicitThis Raise error on 'this' expressions with an implied 'any' type. --alwaysStrict Parse in strict mode and emit "use strict" for each source file. --noUnusedLocals Report errors on unused locals. --noUnusedParameters Report errors on unused parameters. --noImplicitReturns Report error when not all code paths in function return a value. --noFallthroughCasesInSwitch Report errors for fallthrough cases in switch statement. --types Type declaration files to be included in compilation. --esModuleInterop Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. @<file> Insert command line options and files from a file.

載入擴充套件模組:

C:\Users\User-Dai\IdeaProjects\Type-Script\ts-01>tsc --module
error TS6044: Compiler option 'module' expects an argument.
error TS6046: Argument for '--module' option must be: 'none', 'commonjs', 'amd', 'system', 'umd', 'es6', 'es2015', 'es2020', 'esnext'.

設定ECMA版本:

C:\Users\User-Dai\IdeaProjects\Type-Script\ts-01>tsc --target
error TS6044: Compiler option 'target' expects an argument.
error TS6046: Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es2015', 'es2016', 'es2017', 'es2018', 'es2019', 'es2020', 'esnext'.

【TypeScript類與物件】

class Person{
    sayName(name):void {
        console.log("this man, name is " + name);
    }
}

let tom = new Person();
tom.sayName("tom");

被編譯後的JS檔案:

var Person = /** @class */ (function () {
    function Person() {
    }
    Person.prototype.sayName = function (name) {
        console.log("this man, name is " + name);
    };
    return Person;
}());
var tom = new Person();
tom.sayName("tom");

再交給NodeJS執行:

C:\Users\User-Dai\IdeaProjects\Type-Script\ts-01>node ts-test-01.js
this man, name is tom

【變數宣告】

TypeScript 變數的命名規則:

1、變數名稱可以包含數字和字母。
2、除了下劃線 _ 和美元 $ 符號外,不能包含其他特殊字元,包括空格。
3、變數名不能以數字開頭。

TypeScript支援二種方式來宣告變數:

第一種原生JS宣告:

var [變數名] = 值;

例如:
var uname = "Runoob";

第二種TS指定資料型別宣告:

var [變數名] : [型別] = 值;

例如:
var uname:string = "Runoob";

或者可以只宣告變數而不進行任何賦值:

var uname;
var uname:string;

強型別遵循,如果將不同的型別賦值給變數會編譯錯誤,如下例項:

var num:number = "hello"     // 這個程式碼會編譯錯誤

【型別斷言(Type Assertion)】

型別斷言可以用來手動指定一個值的型別,即允許變數從一種型別更改為另一種型別

語法 Syntax:

<型別>值 
或者:
值 as 型別

案例:

var str = '1'
var str2:number = <number> <any> str   //str、str2 是 string 型別
console.log(typeof str2)

【型別推斷】

當型別沒有給出時,TypeScript 編譯器利用型別推斷來推斷型別。

如果由於缺乏宣告而不能推斷出型別,那麼它的型別被視作預設的動態 any 型別。

var num = 2;    // 型別推斷為 number
console.log("num 變數的值為 "+num); 
num = "12";    // 編譯錯誤
console.log(num);

【變數作用域】

1、全域性變數

2、類成員變數

3、區域性變數

var global_num = 12          // 全域性變數
class Numbers { 
   num_val = 13;             // 例項變數
   static sval = 10;         // 靜態變數
   
   storeNum():void { 
      var local_num = 14;    // 區域性變數
   } 
} 
console.log("全域性變數為: "+global_num)  
console.log(Numbers.sval)   // 靜態變數
var obj = new Numbers(); 
console.log("例項變數: "+obj.num_val)

編譯後的JS:

var global_num = 12; // 全域性變數
var Numbers = /** @class */ (function () {
    function Numbers() {
        this.num_val = 13; // 例項變數
    }
    Numbers.prototype.storeNum = function () {
        var local_num = 14; // 區域性變數
    };
    Numbers.sval = 10; // 靜態變數
    return Numbers;
}());
console.log("全域性變數為: " + global_num);
console.log(Numbers.sval); // 靜態變數
var obj = new Numbers();
console.log("例項變數: " + obj.num_val);

NodeJS執行:

C:\Users\User-Dai\IdeaProjects\Type-Script\ts-01>node ts-test-01.js
全域性變數為: 12
10
例項變數: 13

TypeScript的函式需要宣告函式返回型別,或者和原生JS一樣不宣告也是可以的:

// 函式定義
function greet():string { // 返回一個字串
    return "Hello World" 
} 

有一個好處就是有型別我們才知道這個函式的引數到底是需要什麼:

function add(x: number, y: number): number {
    return x + y;
}
console.log(add(1,2))

但是給JS編譯之後就沒有型別限制了

function add(x, y) {
    return x + y;
}
console.log(add(1, 2));

【可選引數】

TypeScript支援可選引數,注意不是可變引數:

當第二引數lastName存在,返回if程式碼塊

否則返回else程式碼塊

function buildName(firstName: string, lastName?: string) {
    if (lastName)
        return firstName + " " + lastName;
    else
        return firstName;
}
 
let result1 = buildName("Bob");  // 正確
let result2 = buildName("Bob", "Adams", "Sr.");  // 錯誤,引數太多了
let result3 = buildName("Bob", "Adams");  // 正確

【預設引數值】

即一些情況下我們可以不顯示的宣告引數的值,預設一個固定的值注入

function calculate_discount(price:number,rate:number = 0.50) { 
    var discount = price * rate; 
    console.log("計算結果: ",discount); 
} 
calculate_discount(1000) 
calculate_discount(1000,0.30)

編譯後的JS:

function calculate_discount(price, rate) {
    if (rate === void 0) { rate = 0.50; }
    var discount = price * rate;
    console.log("計算結果: ", discount);
}
calculate_discount(1000);
calculate_discount(1000, 0.30);

但是注意:引數不能同時設定為可選和預設!

【剩餘引數】

其實就是可變引數:

function buildName(firstName: string, ...restOfName: string[]) {
    return firstName + " " + restOfName.join(" ");
}
  
let employeeName = buildName("Joseph", "Samuel", "Lucas", "MacKinzie");

【匿名函式自呼叫】

(function () { 
    var x = "Hello!!";   
    console.log(x)    
})()

就是說當我們的函式沒有名字,也沒有變數引用

自己宣告自己呼叫的時候:

一是需要把自己用括號包裹,二是引數列表的括號

看起來挺奇怪的。。。

【過載】

基於型別限制,我們又可以實現強型別語言中的方法過載:

function disp(s1:string):void; 
function disp(n1:number,s1:string):void; 
 
function disp(x:any,y?:any):void { 
    console.log(x); 
    console.log(y); 
} 
disp("abc") 
disp(1,"xyz");