`

TypeScript Usage

阅读更多
REM init并产生tsconfig.json
tsc --init

REM compile command
tsc


ref
https://www.typescriptlang.org/docs/handbook/tsconfig-json.html


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

    /* Basic Options */
    // "incremental": true,                         /* Enable incremental compilation */
    "target": "es5",                                /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
    "module": "commonjs",                           /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', 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', 'react', 'react-jsx' or 'react-jsxdev'. */
    // "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": "lib",                                /* 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": true,        /* 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. */
    // "noUncheckedIndexedAccess": true,            /* Include 'undefined' in index signature results */
    // "noPropertyAccessFromIndexSignature": true,  /* Require undeclared properties from index signatures to use element accesses. */

    /* 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 */
    "skipLibCheck": true,                           /* Skip type checking of declaration files. */
    "forceConsistentCasingInFileNames": true        /* Disallow inconsistently-cased references to the same file. */
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "**/*.spec.ts"],
  "files": [
    "hello.ts",
    "basic.ts"
  ]
}



var x;
var y;
// 运行错误,数字类型不能转为 never 类型
x = 123;
// 运行正确,never 类型可以赋值给 never类型
x = (function () { throw new Error('exception'); })();
// 运行正确,never 类型可以赋值给 数字类型
y = (function () { throw new Error('exception'); })();
// 返回值为 never 的函数可以是抛出异常的情况

function error(message:any) {
    throw new Error(message);
}
// 返回值为 never 的函数可以是无法被执行到的终止点的情况
function loop() {
    while (true) { }
}



var hello = "Hello World!";
console.log(hello);



1命名
1. 使用PascalCase為類型命名。
2. 不要使用I做為介面名首碼。
3. 使用PascalCase為枚舉值命名。
4. 使用camelCase為函數命名。
5. 使用camelCase為屬性或本地變數命名。
6. 不要為私有屬性名添加_首碼。
7. 盡可能使用完整的單詞拼寫命名。

2組件
1. 1個檔對應一個邏輯元件 (比如:解析器,檢查器)。
2. 不要添加新的檔。
3. .generated.*尾碼的檔是自動生成的,不要手動改它。

3類型
1. 不要匯出類型/函數,除非你要在不同的組件中共用它。
2. 不要在全域命名空間內定義類型/值。
3. 共用的類型應該在types.ts裡定義。
4. 在一個檔裡,類型定義應該出現在頂部。
null 和 undefined:
1. 使用 undefined,不要使用 null。

4一般假設
1. 假設像Nodes,Symbols等這樣的物件在定義它的元件外部是不可改變的。不要去改變它們。
2. 假設陣列是不能改變的。

5類
1. 為了保持一致,在核心編譯鏈中不要使用類,使用函數閉包代替。

6標記
1. 一個類型中有超過2個布林屬性時,把它變成一個標記。

7注釋
為函數,介面,枚舉類型和類使用JSDoc風格的注釋。

8字串
1. 使用雙引號""
2. 所有要展示給使用者看的資訊字串都要做好本地化工作(在diagnosticMessages.json中創建新的實體)。

9錯誤提示資訊
1. 在句子結尾使用.。
2. 對不確定的實體使用不定冠詞。
3. 確切的實體應該使用名字(變數名,類型名等)
4. 當創建一條新的規則時,主題應該使用單數形式(比如:An external module cannot...而不是External modules cannot)。
5. 使用現在時態。

10錯誤提示資訊代碼
提示資訊被劃分類成了一般的區間。如果要新加一個提示資訊,在上條代碼上加1做為新的代碼。
• 1000 語法資訊
• 2000 語言資訊
• 4000 聲明生成資訊
• 5000 編譯器選項資訊
• 6000 命令列編譯器信息
• 7000 noImplicitAny信息

11普通方法
由於種種原因,我們避免使用一些方法,而使用我們自己定義的。
1. 不使用ECMAScript 5函數;而是使用core.ts這裡的。
2. 不要使用for..in語句;而是使用ts.forEach,ts.forEachKey和ts.forEachValue。注意它們之間的區別。
3. 如果可能的話,嘗試使用ts.forEach,ts.map和ts.filter代替迴圈。

12風格
1. 使用arrow函數代替匿名函數運算式。
2. 只要需要的時候才把arrow函數的參數括起來。
比如,(x) => x + x是錯誤的,下面是正確的做法:
i.	x => x + x
ii.	(x,y) => x + y
iii.	<T>(x: T, y: T) => x ===


3. 總是使用{}把循環體和條件陳述式括起來。
4. 開始的{總是在同一行。
5. 小括弧裡開始不要有空白.
逗號,冒號,分號後要有一個空格。比如:

i.	for (var i = 0, n = str.length; i < 10; i++) { }
ii.	if (x < 10) { }
iii.	function f(x: number, y: string): void { }


6. 每個變數聲明語句只聲明一個變數
(比如 使用 var x = 1; var y = 2; 而不是 var x = 1, y = 2;)。


7. else要在結束的}後另起一行。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics