typescript---1

2020-02-05  本文已影响0人  成熟稳重的李先生

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

//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 = [];

//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是否可以相互引用

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 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)
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会自动判断赋值的类型,并且将这个类型指定给这个变量

let str:string;
str = null;  // 以下两个赋值在`strictNullChecks=false`(在tsconfig.json中配置)时不报错
str = undefined;

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

function gretting(name:string): void{  //即不返回
    return 1; //报错
    return '1'; //报错
    return {}; //报错
    return undefined;//等同于无返回值, 不报错
    return; //同上
    return null; //在strictNullChecks=false时, 不报错
}
// 返回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) {}
}
// 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 无法被观察
  }
}
let name: string | number;
console.log((name as string).length);
console.log((name as number).toFixed(2));
let name: 1|2|3|"a"|true;  //name的取值就介于1|2|3|"a"|true之间,否则报错
上一篇下一篇

猜你喜欢

热点阅读