typescript---1

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

  • 1.首先全局安装typescript
    typescript文件的后缀是ts
    运行命令tsc xxx.ts,会编译出相应的xxx.js文件。
//demo.ts 文件
let name:string = ''; //即 let name = '';只是name的类型被限制为string
let age:number; //即 let age; 只是age的类型被限制为number
let arr:number[]=[]; //即let arr = [];只是arr中的每一项被限定为number类型
//以上数组类型还可以这样定义
let arr1:Array<number>=[]
//元组(固定长度,固定类型的数组)
let position:[number, number] = [100, 100];  //比如经纬度

编译后

//demo.js
var name = ''; //即 let name = '';只是name的类型被限制为string
var age; //即 let age; 只是age的类型被限制为number
var arr = []; //即let arr = [];只是arr中的每一项被限定为number类型
//以上数组类型还可以这样定义
var arr1 = [];
    1. typescript文件可以根据需要编译出不同的js文件
      运行tsc --init,会自动生成一个tsconfig.js文件

//tsconfig.json
{
  "compilerOptions": {
    /* Basic Options */
    // "incremental": true,                   /* Enable incremental compilation */
    "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
    "module": "es2015",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
    // "lib": [],                             /* Specify library files to be included in the compilation. */
    // "allowJs": true,                       /* Allow javascript files to be compiled. */
    // "checkJs": true,                       /* Report errors in .js files. */
    // "jsx": "preserve",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
    // "declaration": true,                   /* Generates corresponding '.d.ts' file. */
    // "declarationMap": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */
    // "sourceMap": true,                     /* Generates corresponding '.map' file. */
    // "outFile": "./",                       /* Concatenate and emit output to single file. */
    // "outDir": "./",                        /* Redirect output structure to the directory. */
    // "rootDir": "./",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "composite": true,                     /* Enable project compilation */
    // "tsBuildInfoFile": "./",               /* Specify file to store incremental compilation information */
    // "removeComments": true,                /* Do not emit comments to output. */
    // "noEmit": true,                        /* Do not emit outputs. */
    // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
    // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

    /* Strict Type-Checking Options */
    "strict": true,                           /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */
    "strictNullChecks": true,              /* Enable strict null checks. */
    // "strictFunctionTypes": true,           /* Enable strict checking of function types. */
    // "strictBindCallApply": true,           /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
    "strictPropertyInitialization": false,  /* Enable strict checking of property initialization in classes. */
    // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */

    /* Additional Checks */
    // "noUnusedLocals": true,                /* Report errors on unused locals. */
    // "noUnusedParameters": true,            /* Report errors on unused parameters. */
    // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
    // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */

    /* Module Resolution Options */
    // "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    // "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
    // "paths": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
    // "typeRoots": [],                       /* List of folders to include type definitions from. */
    // "types": [],                           /* Type declaration files to be included in compilation. */
    // "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    "esModuleInterop": true,                  /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */
    // "allowUmdGlobalAccess": true,          /* Allow accessing UMD globals from modules. */

    /* Source Map Options */
    // "sourceRoot": "",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "",                         /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    /* Experimental Options */
    "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
    // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */

    /* Advanced Options */
    "forceConsistentCasingInFileNames": true  /* Disallow inconsistently-cased references to the same file. */
  }
}

target是编译后的目标语言(es3,es5...)
module是编译后的文件执行的环境(commonjs,amd,es2015...)
要在ts文件中使用commonjs语法(require,...)的话,必须安装node的声明文件@types/node
esModuleInterop表示commonjs和esModule是否可以相互引用

  • 3.枚举
    typescript引入了枚举(enum)类型
enum Gender {
    BOY,
    GIRL
}
console.log(Gender.BOY, Gender.GIRL) // 0, 1

相当于

var Gender = {}
Gender[0] = "BOY";
Gender[1] = "GIRL";
Gender["BOY"]=0;
Gender["GIRL"]=0;

默认索引是从0开始的,当然,你可以自己执行索引

enum Week {
    Mondy=1,
    Tuesday=2
}
console.log(Week) //{ '1': 'Monday', '2': 'Tuesday', Monday: 1, Tuesday: 2 }
  • 常数枚举与普通枚举的区别是,它会在编译阶段被删除,并且不能包含计算成员。
  • 假如包含了计算成员,则会在编译阶段报错
    常数枚举和普通枚举的区别是,常数枚举前有关键字 const
const enum Color {
  RED,
  YELLOW,
  BLUE
}
console.log(Color.RED,Color.YELLOW,Color.BLUE);  
console.log(Color[0],Color[1],Color[2]);  //报错

相当于

console.log(0,1,2)
    1. any类型
      如果定不了一个变量的类型,可以将它定义为any类型(这意味着,你放弃了typescript的类型检查,和普通js一致)。这样,永远也不会报错(编译时)
let root: null | HTMLElement = document.getElementById("root"); //HTMLElement是typescript的内置类型(html元素)
root.style.color = "red"  //这里会报错,因为root可能为null
//解决办法是
(root as any).style.color = "red";
//或者使用非空断言
root!.style.color = "red"; //即root肯定不是空

如果定义一个变量时,既不赋值,也不指定类型,那么它就是any类型
即:

let root; //这样,就和原生js一样了

如果只赋值,但是没有指定类型,那么ts会自动判断赋值的类型,并且将这个类型指定给这个变量

  • 5.null类型
  • null 和 undefined 是其它类型的子类型,可以赋值给其它类型,如数字类型,此时,赋值后的类型会变成 null 或 undefined
  • strictNullChecks (是否进行严格null检查)参数用于新的严格空检查模式,在严格空检查模式下, null 和 undefined 值都不属于任何一个类型,它们只能赋值给自己这种类型或者 any
let str:string;
str = null;  // 以下两个赋值在`strictNullChecks=false`(在tsconfig.json中配置)时不报错
str = undefined;

当strictNullChecks=true时,null类型的变量不能赋undefined,undefined类型也不能赋null

  • 6.void类型(空类型)
  • void 表示没有任何类型
  • 当一个函数没有返回值时,TS 会认为它的返回值是 void 类型。
function gretting(name:string): void{  //即不返回
    return 1; //报错
    return '1'; //报错
    return {}; //报错
    return undefined;//等同于无返回值, 不报错
    return; //同上
    return null; //在strictNullChecks=false时, 不报错
}
  • 7.never类型
  • never是其它类型(null undefined)的子类型,代表不会出现的值,一般用作函数,代表不能正常返回(1.函数中间抛异常了,2.函数中有死循环)
// 返回never的函数 必须存在 无法达到( unreachable ) 的终点
function error(message: string): never {
    throw new Error(message);
}
let result1 = error('hello');
// 由类型推论得到返回值为 never
function fail() {
    return error("Something failed");
}
let result = fail();

// 返回never的函数 必须存在 无法达到( unreachable ) 的终点
function infiniteLoop(): never {
    while (true) {}
}
  • 8.strictNullChecks
  • 在 TS 中, null 和 undefined 是任何类型的有效值,所以无法正确地检测它们是否被错误地使用。于是 TS 引入了 --strictNullChecks 这一种检查模式
  • 由于引入了 --strictNullChecks ,在这一模式下,null 和 undefined 能被检测到。所以 TS 需要一种新的底部类型( bottom type )。所以就引入了 never。
// Compiled with --strictNullChecks
function fn(x: number | string) {
  if (typeof x === 'number') {
    // x: number 类型
  } else if (typeof x === 'string') {
    // x: string 类型
  } else {
    // x: never 类型
    // --strictNullChecks 模式下,这里的代码将不会被执行,x 无法被观察
  }
}
    1. never 和 void 的区别
  • void 可以被赋值为 null 和 undefined的类型。 never 则是一个不包含值的类型。

  • 拥有 void 返回值类型的函数能正常运行。拥有 never 返回值类型的函数无法正常返回,无法终止,或会抛出异常。

  • 10.类型断言

    • 类型断言可以将一个联合类型的变量,指定为一个更加具体的类型
    • 不能将联合类型断言为不存在的类型
let name: string | number;
console.log((name as string).length);
console.log((name as number).toFixed(2));
  • 11.字面量类型
    • 可以把字符串、数字、布尔值字面量组成一个联合类型
let name: 1|2|3|"a"|true;  //name的取值就介于1|2|3|"a"|true之间,否则报错
  • 12.字符串字面量 vs 联合类型
    • 字符串字面量类型用来约束取值只能是某几个字符串中的一个, 联合类型(Union Types)表示取值可以为多种类型中的一种
    • 字符串字面量 限定了使用该字面量的地方仅接受特定的值,联合类型 对于值并没有限定,仅仅限定值的类型需要保持一致
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,525评论 6 507
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,203评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,862评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,728评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,743评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,590评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,330评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,244评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,693评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,885评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,001评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,723评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,343评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,919评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,042评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,191评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,955评论 2 355

推荐阅读更多精彩内容

  • 主要目的是为补充 javascript 语言类型系统的超集 typescript,自然后从各个角度全方位地关注 j...
    zidea阅读 477评论 0 2
  • 最近一些出去面试的学生,被问及最多的,除了那些常用的框架,比如Angular.js,Vue.js等等,除此之外,还...
    殷灬商阅读 818评论 0 3
  • 这一章主要总结TypeScript的用法和项目常用配置 编译上下文 用来给文件分组,告诉 TypeScript 哪...
    Terryzh阅读 2,012评论 0 0
  • 简介 TypeScript 是 JavaScript 的一个超集,主要提供了 类型系统 和对 ES6 的支持,由 ...
    MrWelson阅读 15,906评论 3 21
  • 简介 TypeScript 是 JavaScript 的一个超集,主要提供了 类型系统 和对 ES6 的支持,由 ...
    _往后_阅读 856评论 0 1