安装 npm i -g typescript
- 基本类型
// 声明一个变量,指定得类型为number,以后是要用过程中a的值只能是数字
let a : number;
// 如果变量的声明和赋值是同时进行的,ts了可以自动对变量进行类型检测
let b = true;
// 函数,返回值是number
function sum(a: number ,b: number): number{
return a + b
}
let result = sum(123, 456);
// 可以使用|来链接多个类型(联合类型)
let huo = 'hellow' | 'worl';
// any 表示的是任意类型,一个变量设置类型为any后相当于对该变量关闭了ts的类型检测
// 申明变量如果不指定类型,zets会自动判断变量的类型为any(隐士any)
let d : any;
// unknown 表示位置类型的值
// void 用来表示空,一函数为例,就表示没有返回值的函数
function fn():void{ }
// never 表示永远不会返回结果
// {} 用来表示指定对象中可以包含那些属性,后边加?。表示属性是可选的
let obj: {name: string,age?: number}
// 表示任意类型的属性
let c = {name:string,[propNmae:string]:any}
// [] 数组,
let str = string[]; // 字符换数组
let str2 = number[]; // 数值数组
str = ['a','b','c']
str2 = [0,1,2,5,5]
// enum 枚举
- 编译
- txc xxx.ts -w
{
// tsconfig.jspn 配置文件
// ts编译器的配置文件,可以根据他的信息来代码编译
// inclede,那些文件需要编译 ** 任意目录 *任意文件
// "include": [
// "./src/**/*",
// ],
// // exclude,被排除的文件
// "exclude": [
// "./src/**/*",
// ],
"compilerOptions": {
// 用来指定被编译 的版本 "ES3", "ES5", "ES6", "ES2015", "ES2016", "ES2017", "ES2018", "ES2019", "ES2020", "ES2021", "ES2022", "ESNext".
"target": "es6",
// module 指定要使用的模块化
"module":"ES2015",
// lib 用来指定项目中要使用的库
"lib":[],
// outDir 用来指定编译后文件所在的目录
"outDir": "./dist",
// outFile 将代码设置为一个文件
"outFile": "./dist/app.js",
// 是否对js文件进行编译,默认为false
"allowJs": true,
// 是否检查js代码的语法规范
"checkJs": true,
// 是否移除注释
"removeComments": false,
// 是否生成编译后的文件
"noEmit": false,
// 当有错误时不生成编译后的文件
"noEmitOnError": true,
// 是否为严格模式,
"alwaysStrict": true,
// 默认类型是否为any
"noImplicitAny": false,
}
}