TypeScript使用总结01 - 基本数据类型

102 阅读2分钟

涉及代码仓库

github.com/Dartgm/dart…

TypeScript是什么?

  • TypeScript是由微软开发的一款开源的编程工具
  • TypeScript是JavaScript的超集,遵循最新的ES5/ES6规范,TypeScript扩展了JavaScript的语法
  • TypeScript更像后端Java,C#这样的面向对象的语言,也就是说可以让开发大型企业使用
  • 越来越多的项目是基于TS的,比如VSCode、Angular6、Vue3、React16
  • TS提供的类型系统可以帮助我们在写代码的时候获得更多的语法提示
  • 在创建前的编译阶段经过类型系统的检查,就可以避免很多的线上的错误

TypeScript的安装和编译

安装

cnpm i typescript -g

编译

tsc helloworld.ts

上手实践

首先我们新建一个文件夹,将该文件夹通过命令行工具打开,并且输入 code . 来执行命令

图片.png

然后我们就可以用Vscode这个软件来编辑ts后缀的文件了.输入tsc --init创建tsconfig文件。如下所示

{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig to read more about this file */


    /* Language and Environment */
    "target": "es2016",                                  

    /* Modules */
    "module": "commonjs",                                

    "esModuleInterop": true,                              

    "forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */

    /* Type Checking */
    "strict": true,                                      /* Enable all strict type-checking options. */

    "skipLibCheck": true                                 /* Skip type checking all .d.ts files. */
  }
}
名称描述
target将es编译成特定的es版本
module指定模块默认的生成规范,默认的就是commonjs
// Basic DataStruct introduction

let married:boolean = true;
let age:number = 10;
let first_name:string = 'guoming';
let arr1:number[] = [1,2,3];
let arr2:Array<number> = [4,5,6]


// tuple, number and type are know to us
let guoming:[string,number] = ['guoming',10];


// enum type
enum Gender {
    GIRL,
    BOY
}


// basic enum
console.log(Gender.BOY)
console.log(Gender.GIRL)


// const enum
const enum Colors{
    RED,YELLOW,BLUE
}
let myColor = [Colors.RED,Colors.YELLOW,Colors.BLUE]

// any type,if there is an variable declared to be any,these variable is the same like the variable in JavaScript
let root:any = document.getElementById('root')
root.style.color = 'red'


let element: (HTMLElement|null) = document.getElementById('root');

element.style.color = 'green';

// null undefined
let x:number;
x=1;
x=undefined;
x=null;


let y:(number|null|undefined)

y=1;
y=null;
y=undefined;