打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
typescript[0x01]--基础数据类型
userphoto

2023.02.03 浙江

关注

typescript产自微软,是Javascript的超集。

楼上这句话后半部分听不懂没有关系,下面跟ataola一起通过一些具体实例和思考,来一起学习一下typescript吧!

一、为何要学习typescript

这里我们不得不先说下Javascript,它由ECMAScript、DOM、BOM组成。上古石器时代,那个时候的上古程序员不需要考虑太多,大多数都是静态写死的页面,大致上Javascript扮演的角色就是那种,你打开一个网页弹出一个很挫的框的这类事情,我们暂且亲切地称之为“JS一代”。经过岁月的沉淀,写着写着写出很多祖传代码,慢慢地就有了些积累,也就进入了以JQuery为核心代表的铁器时代,这个时候可以搞一些特效啦,代码可以写的很少,但事情可以做很多,我们亲切地称它为“JS二代”。随后前端进入了移动互联网的时代,以Bootstrap为首的一些响应式框架成为兼容移动端的解决方案。Node.JS的出现,使得Javascript在后端开发有一席之地,这得益于Google的V8引擎,使其有良好的体验。在此之前我一直认为Javascript是一门解释型语言,通过一些列学习,倒是有了不同的看法,也不能说前面的不对吧,但是其内部还是有编译的环节在的。我们可以亲切地称其为“JS三代”。而今,React、Vue、Angular在前端构成”三驾马车“的局面,姑且认为是”JS四代“吧。

从楼上的种种示例表明Javascript足够担当得起”脚本之王“的称号,那么,我们为什么去学Typescript呢?JavaScript语言不同于Java、C#这类强语言会在编译时进行静态类型检查。它是一种弱语言,在运行的时候进行动态类型检查,然后运气好的话,可能打开浏览器的控制台,会冒出你都想不到的”鸡血红“。原因之一是Javascript语言没有其他语言那么多的条条框框,你可以随意地进行类型转换。那么有了Typescript以后,我们自然而然地能够避免很多不必要的错误,一些错误把它提到编译时发现,更加严谨了许多。现阶段,我学习Typescript的主观感受就是类型检查很棒,写起来越来越像Java,什么注解、类型、类、模块、接口啥的都出来了,但这是远远不够的,还需要后期深入学习才能体会到它的一些其它玄学。

二、环境搭建

2.1 、安装

请确保你电脑上装有Node.JS运行环境,如果条件不允许的话,切到淘宝源地址,然后执行楼下这句话

npm i typescript -g

通过tsc --help我们来查看相关命令,看到这里说明你已经安装成功了。

C:\Users\ataola>tsc --help
Version 3.5.3
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' or 'ESNEXT'.
-m KIND, --module KIND                             Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 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.asynciterable' 'es2018.intl' 'es2018.promise' 'es2018.regexp' 'es2019.array' 'es2019.object' 'es2019.string' 'es2019.symbol' 'es2020.string' 'es2020.symbol.wellknown' 'esnext.array' 'esnext.symbol' 'esnext.asynciterable' 'esnext.intl' 'esnext.bigint'
--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\ataola>

2.2、配置

执行npm --init

tsc --init 
message TS6071: Successfully created a tsconfig.json file.

如何使用配置文件,执行楼下命令。

tsc -p ./tsconfig.json

配置项初学者,知道楼下这几个就好。

  • target: 指的就是将ts代码要转换成哪个版本的js代码 es5 es3

  • module: 指的就是将ts代码转换成js代码之后,使用的模块化的标准是什么

  • outDir: 指的就是将ts代码转换成js代码之后,js代码存放的文件夹路径

  • rootDir: 指的就是要将哪个目录中的ts代码进行转换,ts代码的存放路径

  • strict: 是否要将ts代码转换为严格模式的js代码!

    当然这里你不配置文件,在代码量很少的情况下也是对的,合情合理的。

三、关于数据类型入门例子

布尔值: boolean

var flag:boolean = false;
console.log(!flag);  //true

数字: number

// 二进制
let binaryLiteral: number = 0b001001100101;

//八进制
let octalLiteral: number = 0o1145;

//十进制
let decLiteral: number = 613;

//十六进制
let hexLiterral: number = 0x265;

console.log("二进制数:", binaryLiteral);

console.log("八进制数:", octalLiteral);

console.log("十进制数:", decLiteral);

console.log("十六进制数:", hexLiterral);

这里你在ts文件下写是这样子的,但是当你执行tsc编译成js文件的时候,只有十六进制是不变的,其他的都会被转成十进制,最终的答案显示的也是十进制。

字符串: string

let user1_name: string = "ataola";

let user2_name: string = '阿涛啦';

let user3_name: string = `Eason Zheng`;

let user3_age : number = 23;

let bio = `Hello Everyone, My name is ${user3_name}, and I 'll be ${user3_age + 1} in next years!`;

console.log("user1_name: ", user1_name);
console.log("user2_name: ", user2_name);
console.log("user3_name: ", user3_name);
console.log("bio: ", bio);

这里,单双引号编译成js文件后,还是保持原来的样子,但是模板字符串它会被编译成双引号,而不是仍保持模板字符串。

数组: array

let num_arr1: number[] = [1, 9, 9, 7, 0, 6, 1, 3];

let num_arr2: Array<number> = [1, 9, 9, 7, 0, 6, 1, 3];

let str_arr: string[] = ['hong', 'kong', 'is', 'come', 'back', '!'];

console.log("num_arr1: ", num_arr1);

console.log("num_arr2: ", num_arr2);

console.log("str_arr: ", str_arr);

可以看到,有两种创建方式 number[] 和 Array<number>

元组:Tuple

let tuple1_right: [string, number];
tuple1_right = ['ataola', 23];

console.log("tuple1_right: ", tuple1_right);

元组就是可以产生不同类型元素的数组,但是如楼上所示,把'ataola'和23对调一下就会编译出错,因为在第一句就已经定死了,然后这边我们如果访问一个超出长度的值,例如 tuple1_right[3] = 'xxx',也会报错。然后你放不同类型的例如boolean类型的也是不行的哦。这里也可以用联合类型,“let param = string | number"。

枚举:enum

enum Color{RED, GREEN, BLUE = 613};
let c: Color = Color.BLUE;
let cName: string = Color[613];
console.log("c: ", c);
console.log("cName: ", cName);
const enum Directions {
   Up,
   Down,
   Left,
   Right
};

let directions: number[] = [Directions.Up, Directions.Down, Directions.Left, Directions.Right];
console.log("directions: ", directions);

对JavaScript标准数据类型的一个补充,你可以定义一些有名字的数据常量。枚举值除了第一个外,都有依次加1的规律,除非你自己设置过,默认第一个为0,外部枚举用来描述已经存在的枚举类型的形状。枚举类型默认是从0开始的, 然后你也可以自己给它赋值,如果想取名字的话,那就是对应的值的数组形式。

任意值:any

let unknow: any = 613;
   console.log("number unknow: ", unknow);
   unknow = 'Hello, World!';
   console.log("string unknow: ", unknow);
   unknow = true;
   console.log("boolean unknow: ", unknow);
let unknowArr = ['ataola', 'male', 1997, true];
   console.log("unknowArr: ", unknowArr);

不清楚变量类型,想跳过编译期间的检查

空值:void

function loginInfo(): void {
   console.log("A client logined!");
}

loginInfo();

let param1: void = undefined;
let param2: void = null;

console.log("param1: ", param1);
console.log("param2: ", param2);

一般都是函数见到返回空值较多,声明一个void的变量的话,你只能给它赋值null或者undefined, 你这边放着不写,默认也是前面的情况。

PS: 运行的话 tsc -p ./tsconfig.json,没有指定的话,会在同目录下生成一个js文件。也可以直接进入所在目录 执行 tsc xxx.ts 或者 tsc xxx或者直接tsc也是可以的,默认编译成严格模式的js。

四、问题思考

4.1、Typescript报错,编译能进行吗?编译后的js文件能运行吗?

编译能够进行下去,编译后的js文件也可以运行。

这里我们举一个低配版实现查找数组索引的例子。

index.ts

//一个基于Typescript,数字数组索引查找的实现
interface indexOfFunc {
  (arr: number[], num: number): number;
}

let ataolaFI: indexOfFunc;
ataolaFI = function (arr: number[], num: number) {
   for(let i = 0; i < arr.length; i++){
       if(arr[i] === num){
           return i;
      }
  }
}
console.log("[1, 2, 4, 3, 5]4的索引是: ", ataolaFI([1, 2, 4, 3, 5], 4));

这里我们通过执行”tsc index.ts",发现会报一个楼下的错,但是执行还是可以的。

1.ts:7:1 - error TS2322: Type '(arr: number[], num: number) => number | undefined' is not assignable to type 'indexOfFunc'.
Type 'number | undefined' is not assignable to type 'number'.
  Type 'undefined' is not assignable to type 'number'.

7 ataolaFI = function (arr: number[], num: number) {
~~~~~~~~


Found 1 error.

这里的话少考虑一种情况就是,要是找不到呢?后面改正的代码是

//一个基于Typescript,数字数组索引查找的实现
interface indexOfFunc {
  (arr: number[], num: number): number;
}

let ataolaFI: indexOfFunc;
ataolaFI = function (arr: number[], num: number) {
   for(let i = 0; i < arr.length; i++){
       if(arr[i] === num){
           return i;
      }
  }
   return -1;
}
console.log("[1, 2, 4, 3, 5]的4的索引是: ", ataolaFI([1, 2, 4, 3, 5], 4));

这很大程度上,能让开发巧妙地避开逻辑漏洞。

至此,本文已接近尾声,以上内容是ataola童鞋学习时候的总结,水平有限,可能不一定都对的,若有错误,供批评指正。最后,感谢您的收听!

typescript官网:  http://www.typescriptlang.org/

官方在线运行:  http://www.typescriptlang.org/play/?ssl=2&ssc=22&pln=1&pc=1#

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
TypeScript---数据类型
TypeScript 入门教程 | 菜鸟教程
使用 TypeScript 编写 SAP UI5 应用的准备工作
vue3系列—TypeScript
typescript
TypeScript---介绍,安装和开发工具
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服