美文网首页
typescript---1

typescript---1

作者: 成熟稳重的李先生 | 来源:发表于2020-02-05 20:58 被阅读0次

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)表示取值可以为多种类型中的一种
    • 字符串字面量 限定了使用该字面量的地方仅接受特定的值,联合类型 对于值并没有限定,仅仅限定值的类型需要保持一致

相关文章

  • typescript---1

    Typescript是由微软开发的一款开源的编程语言Typescript是Javascript的超集,遵循最新的E...

网友评论

      本文标题:typescript---1

      本文链接:https://www.haomeiwen.com/subject/dgtxactx.html