全局安装typescript: npm install -g typescript
生成配置文件tsconfig.json: tsc --init
大致结构如下(3.9.6):
{
"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', 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": 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. */
/* 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. */
}
}
编译相关的选项
项目选项
incremenal
target
module
lib
指定引入的声明文件,就是js或浏览器环境内置API的生命文件。默认会根据你配置的 target,来导入对应的声明文件。例如Map可以在target为ES6+才可以使用。
指定内置API声明组的列表。只引入API的声明文件,不会引入pollyfill。如果要引入pollyfill, 可借助Babel。
一般如下情况你才需要修改此选项:
- 程序不运行在浏览器里,因此不需要 dom 的类型定义
- 运行环境提供了某些API对象(或许是pollyfills),但是设置的target环境版本并不支持
如果没有指定声明文件列表,那么将根据target参数默认导入特定声明文件,映射关系如下:
For --target ES5: DOM,ES5,ScriptHost
For --target ES6: DOM,ES6,DOM.Iterable,ScriptHost
allowjs
checkjs
jsx
declaration
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
类型相关的选项包括 typeRoots
和 types
。
有一个普遍的误解,以为这两个选项适用于所有的类型声明文件,包括用户自定义的声明文件。其实不然。
这两个选项只对通过 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"]
}
}
只会引入 node
、 lodash
和 express
三个声明模块,其它的声明模块则不会被自动引入。
如果 types
被设置为 []
,那么将不会自动引入任何声明模块。此时,如果想使用声明模块,只能在代码中手动引入了。
请记住,自动引入只对包含全局声明的模块有效。比如 jQuery
,我们不用手动 import
或者 ///<reference/>
即可在任何文件中使用 $
的类型。再比如,对于 import 'foo'
,编译器会分别在 node_modules
和 node_modules/@types
文件下查找 foo
模块和声明模块。
基于此,如果想让自定义声明的类型不需要手动引入就可以在任何地方使用,可以将其声明为全局声明 global
,然后让 files
或者 include
包含即可。
比如:
declare global {
const graphql: (query: TemplateStringsArray) => void;
namespace Gatsby {
interface ComponentProps {
children: () => React.ReactNode,
data: RootQueryType
}
}
}
这样的话,就可以在任何地方直接使用 graphql
和 Gatsby
对应的类型了。