全局安装typescript: npm install -g typescript
生成配置文件tsconfig.json: tsc --init
大致结构如下(3.9.6):

  1. {
  2. "compilerOptions": {
  3. /* Visit https://aka.ms/tsconfig.json to read more about this file */
  4. /* Basic Options */
  5. // "incremental": true, /* Enable incremental compilation */
  6. "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
  7. "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
  8. // "lib": [], /* Specify library files to be included in the compilation. */
  9. // "allowJs": true, /* Allow javascript files to be compiled. */
  10. // "checkJs": true, /* Report errors in .js files. */
  11. // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
  12. // "declaration": true, /* Generates corresponding '.d.ts' file. */
  13. // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
  14. // "sourceMap": true, /* Generates corresponding '.map' file. */
  15. // "outFile": "./", /* Concatenate and emit output to single file. */
  16. // "outDir": "./", /* Redirect output structure to the directory. */
  17. // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
  18. // "composite": true, /* Enable project compilation */
  19. // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
  20. // "removeComments": true, /* Do not emit comments to output. */
  21. // "noEmit": true, /* Do not emit outputs. */
  22. // "importHelpers": true, /* Import emit helpers from 'tslib'. */
  23. // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
  24. // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
  25. /* Strict Type-Checking Options */
  26. "strict": true, /* Enable all strict type-checking options. */
  27. // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
  28. // "strictNullChecks": true, /* Enable strict null checks. */
  29. // "strictFunctionTypes": true, /* Enable strict checking of function types. */
  30. // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
  31. // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
  32. // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
  33. // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
  34. /* Additional Checks */
  35. // "noUnusedLocals": true, /* Report errors on unused locals. */
  36. // "noUnusedParameters": true, /* Report errors on unused parameters. */
  37. // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
  38. // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
  39. /* Module Resolution Options */
  40. // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
  41. // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
  42. // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
  43. // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
  44. // "typeRoots": [], /* List of folders to include type definitions from. */
  45. // "types": [], /* Type declaration files to be included in compilation. */
  46. // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
  47. "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
  48. // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
  49. // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
  50. /* Source Map Options */
  51. // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
  52. // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
  53. // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
  54. // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
  55. /* Experimental Options */
  56. // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
  57. // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
  58. /* Advanced Options */
  59. "skipLibCheck": true, /* Skip type checking of declaration files. */
  60. "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
  61. }
  62. }

编译相关的选项

默认值与生成的默认配置文件一直

项目选项

incremenal

启动增量编译
default: true

target

输出的js版本号
default: es5

module

模块类型
default: commonjs

lib

指定引入的声明文件,就是js或浏览器环境内置API的生命文件。默认会根据你配置的 target,来导入对应的声明文件。例如Map可以在target为ES6+才可以使用。
指定内置API声明组的列表。只引入API的声明文件,不会引入pollyfill。如果要引入pollyfill, 可借助Babel。

一般如下情况你才需要修改此选项:

  • 程序不运行在浏览器里,因此不需要 dom 的类型定义
  • 运行环境提供了某些API对象(或许是pollyfills),但是设置的target环境版本并不支持

查看所有的API声明文件列表。

如果没有指定声明文件列表,那么将根据target参数默认导入特定声明文件,映射关系如下:

For --target ES5: DOM,ES5,ScriptHost
For --target ES6: DOM,ES6,DOM.Iterable,ScriptHost

allowjs

允许编译js文件
default: true

checkjs

检查js文件错误
default: true

jsx

jsx代码的生成方式
default: preserve

declaration

生成相应的.d.ts文件
default: true

declarationMap

为.d.ts文件生成sourcemap文件
default: true

sourcemap

outFile

outdir

rootDIr

composite

tsBuilderFile

removeComments

noEmit

importHelper

downLevelLiterator

isolatedMudules

严格类型

模块解析

esModuleInterop: false

导入非esmodule时,按默认导入(Import non-ES modules as default imports)

为babel生态系统兼容性,生成 importStar 和 importDefault 帮助方法,并为类型系统兼容性启用’—allowSyntheticDefaultImports’。就是你开启该选项,allowSyntheticDefaultImports 也会默认开启

importStar 和 importDefault 帮助方法如下:

var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};

allowSyntheticDefaultImports: false

类型:boolean; 默认:false;
允许对不包含默认导出的模块使用默认导入。这个选项不会影响生成的代码,只会影响类型检查。

export = foo 是 ts 为了兼容 commonjs 创造的语法,它对应于 commonjs 中的 module.exports = foo

在 ts 中,如果要引入一个通过 export = foo 导出的模块,标准的语法是 import foo = require('foo'),或者 import * as foo from 'foo'

但由于历史原因,我们已经习惯了使用 import foo from 'foo'

这个选项就是为了解决这个问题。当它设置为 true 时,允许使用 import foo from 'foo' 来导入一个通过 export = foo 导出的模块。当它设置为 false 时,则不允许,会报错。

当然,我们一般不会在 ts 文件中使用 export = foo 来导出模块,而是在写(符合 commonjs 规范的)第三方库的声明文件时,才会用到 export = foo 来导出类型。

比如 React 的声明文件中,就是通过 export = React 来导出类型:

export = React;
export as namespace React;
declare namespace React {
// 声明 React 的类型
}

baseUrl

参考

paths

typeRoots

类型相关的选项包括 typeRootstypes
有一个普遍的误解,以为这两个选项适用于所有的类型声明文件,包括用户自定义的声明文件。其实不然。
这两个选项只对通过 npm 安装的声明模块有效,用户自定义的类型声明文件与它们没有任何关系
声明模块通常会包含一个 index.d.ts 文件,或者其 package.json 设置了 types 字段。
默认的,所有位于 node_modules/@types 路径下的模块都会引入到编译器。
具体来说是,./node_modules/@types../node_modules/@types../../node_modules/@types 等等。
typeRoots 用来指定默认的类型声明文件查找路径,默认为 node_modules/@types 。比如:

{
  "compilerOptions": {
    "typeRoots": ["./typings"]
  }
}

上面的配置会自动引入 ./typings 下的所有 TS 类型声明模块,而不是 ./node_modules/@types 下的模块。
如果不希望自动引入 typeRoots 指定路径下的所有声明模块,那可以使用 types 指定自动引入哪些模块。比如:

{
  "compilerOptions": {
    "types" : ["node", "lodash", "express"]
  }
}

只会引入 nodelodashexpress 三个声明模块,其它的声明模块则不会被自动引入。
如果 types 被设置为 [] ,那么将不会自动引入任何声明模块。此时,如果想使用声明模块,只能在代码中手动引入了。
请记住,自动引入只对包含全局声明的模块有效。比如 jQuery ,我们不用手动 import 或者 ///<reference/> 即可在任何文件中使用 $ 的类型。再比如,对于 import 'foo' ,编译器会分别在 node_modulesnode_modules/@types 文件下查找 foo 模块和声明模块。
基于此,如果想让自定义声明的类型不需要手动引入就可以在任何地方使用,可以将其声明为全局声明 global ,然后让 files 或者 include 包含即可。
比如:

declare global {
  const graphql: (query: TemplateStringsArray) => void;
  namespace Gatsby {
    interface ComponentProps {
      children: () => React.ReactNode,
      data: RootQueryType
    }
  }
}

这样的话,就可以在任何地方直接使用 graphqlGatsby 对应的类型了。

types

参考

TSConfig Reference.
了不起的 tsconfig.json 指南