【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");

猜你喜欢

转载自www.cnblogs.com/mindzone/p/13389392.html