You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Report errors in .js files. Use in conjunction with --allowJs.
和allowjs一起使用,js文件里有错误的时候,是否报错。
// -- checkJs true
// index.js
import { a } from 'test'
a('1324') // error TS2345: Argument of type '"1324"' is not assignable to parameter of type 'number'.
// test.ts
export function a(i: number) {
return i
}
Provide full support for iterables in for..of, spread and destructuring when targeting ES5 or ES3.
在生成目标代码为es5或者es3的时候,提供对 for..of, spread and destructuring语法的支持。
相当于提供polyfill
let a = [1, 2, 3]
let b = [4, ...a]
此选项为false时,转换为
var a = [1, 2, 3];
var b = [4].concat(a);
此选项为true时,转换成:
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spread = (this && this.__spread) || function () {
for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));
return ar;
};
var a = [1, 2, 3];
var b = __spread([4], a);
emitBOM
Option
Type
Default
Desc
--emitBOM
boolean
false
Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files.
生成的文件是否要带BOM头
esModuleInterop
Option
Type
Default
Desc
--esModuleInterop
boolean
false
Emit __importStar and __importDefault helpers for runtime babel ecosystem compatibility and enable --allowSyntheticDefaultImports for typesystem compatibility.
"use strict";
exports.__esModule = true;
exports.a = 100;
var b = 200;
exports["default"] = exports.a;
forceConsistentCasingInFileNames
Option
Type
Default
Desc
--forceConsistentCasingInFileNames
boolean
false
Disallow inconsistently-cased references to the same file.
是否在导入文件的时候需要保证大小写一致。
和文件名是否一致不重要,但多次导入的时候大小写一定要一致。
// Test.ts
let a = 1
export default a
import a from './test' // 导入小写,没问题
import b from './Test' // 再导入大写,报错。 error TS1149: File name '/Users/leon/Documents/git/typescript-options/forceConsistentCasingInFileNames/Test.ts' differs from already included file name '/Users/leon/Documents/git/typescript-options/forceConsistentCasingInFileNames/test.ts' only in casing.
experimentalDecorators
Option
Type
Default
Desc
--experimentalDecorators
boolean
false
Enables experimental support for ES decorators.
启动实验的装饰器功能。
importHelpers
Option
Type
Default
Desc
--importHelpers
boolean
false
Import emit helpers (e.g. __extends, __rest, etc..) from tslib
是否从tslib里导入__extends, __rest等helper函数
这个选项似乎已经没有什么用了。
let b = {
name: 'leon'
}
let a = {
age: 10,
...b
}
无论此项如何设置,始终会转换成:
var __assign = (this && this.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
var b = {
name: 'leon'
};
var a = __assign({ age: 10 }, b);
inlineSourceMap
Option
Type
Default
Desc
--inlineSourceMap
boolean
false
Emit a single file with source maps instead of having a separate file.
是否生成inline的source map
上栗中的代码,加本选项编译,文件末尾会多出sourcemap:
//# sourceMappingURL= xxxxxxx
inlineSources
Option
Type
Default
Desc
--inlineSourceMap
boolean
false
Emit the source alongside the sourcemaps within a single file; requires --inlineSourceMap or --sourceMap to be set.
List of library files to be included in the compilation. Possible values are: ► ES5 ► ES6 ► ES2015 ► ES7 ► ES2016 ► ES2017 ► ESNext ► DOM ► DOM.Iterable ► WebWorker ► ScriptHost ► ES2015.Core ► ES2015.Collection ► ES2015.Generator ► ES2015.Iterable ► ES2015.Promise ► ES2015.Proxy ► ES2015.Reflect ► ES2015.Symbol ► ES2015.Symbol.WellKnown ► ES2016.Array.Include ► ES2017.object ► ES2017.SharedMemory ► ES2017.TypedArrays ► esnext.asynciterable ► esnext.array ► esnext.promise
Note: If --lib is not specified a default list of librares are injected. The default libraries injected are: ► For --target ES5: DOM,ES5,ScriptHost ► For --target ES6: DOM,ES6,DOM.Iterable,ScriptHost
export default function test() {
let a = 1
let b = new Promise(resolve => {
resolve(1)
})
return a
}
// tsc lib/index.ts --lib ES5
// error TS2693: 'Promise' only refers to a type, but is being used as a value here.
// tsc lib/index.ts --lib ES6
// build pass
listEmittedFiles
Option
Type
Default
Desc
--listEmittedFiles
boolean
false
Print names of generated files part of the compilation.
The locale to use to show error messages, e.g. en-us. Possible values are: ► English (US): en ► Czech: cs ► German: de ► Spanish: es ► French: fr ► Italian: it ► Japanese: ja ► Korean: ko ► Polish: pl ► Portuguese(Brazil): pt-BR ► Russian: ru ► Turkish: tr ► Simplified Chinese: zh-CN ► Traditional Chinese: zh-TW
Specifies the location where debugger should locate map files instead of generated locations. Use this flag if the .map files will be located at run-time in a different location than the .js files. The location specified will be embedded in the sourceMap to direct the debugger where the map files will be located.
--sourceRoot
string
Specifies the location where debugger should locate TypeScript files instead of source locations. Use this flag if the sources will be located at run-time in a different location than that at design-time. The location specified will be embedded in the sourceMap to direct the debugger where the source files will be located.
- maxNodeModuleJsDepth
- index.ts
- node_modules
- test1
- index.js
- node_modules
- test2
- index.js
// maxNodeModuleJsDepth/index.ts
import a from 'test1' // maxNodeModuleJsDepth设置成什么,这句总是对的
import b from 'test2' // 这句总是错的。
可能我的理解有误。
module
Option
Type
Default
Desc
--module -m
string
target === "ES3" or "ES5" ? "CommonJS" : "ES6"
Specify module code generation: "None", "CommonJS", "AMD", "System", "UMD", "ES6", "ES2015" or "ESNext". ► Only "AMD" and "System" can be used in conjunction with --outFile. ► "ES6" and "ES2015" values may be used when targeting "ES5" or lower.
指定生成代码的模块格式
// index.ts
export function test() {
return 'hello'
}
// -module system
System.register([], function (exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
function test() {
return 'hello';
}
exports_1("test", test);
return {
setters: [],
execute: function () {
}
};
});
// -module UMD
(function (factory) {
if (typeof module === "object" && typeof module.exports === "object") {
var v = factory(require, exports);
if (v !== undefined) module.exports = v;
}
else if (typeof define === "function" && define.amd) {
define(["require", "exports"], factory);
}
})(function (require, exports) {
"use strict";
exports.__esModule = true;
function test() {
return 'hello';
}
exports.test = test;
});
// -module es6 or es2015 or esnext
export function test() {
return 'hello';
}
target
Option
Type
Default
Desc
--target -t
string
"es3"
Specify ECMAScript target version: "ES3" (default), "ES5", "ES6"/"ES2015", "ES2016", "ES2017" or "ESNext". Note: "ESNext" targets latest supported ES proposed features.
指定目标代码的版本。
// index.ts
export function test() {
return new Promise(resolve => {
resolve(1)
})
}
// --target es3
"use strict";
var __assign = (this && this.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
exports.__esModule = true;
function test() {
return new Promise(function (resolve) {
var a = {
a: 1,
b: 2
};
resolve(__assign({ c: 3 }, a));
});
}
exports.test = test;
// --target es5
"use strict";
var __assign = (this && this.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
function test() {
return new Promise(function (resolve) {
var a = {
a: 1,
b: 2
};
resolve(__assign({ c: 3 }, a));
});
}
exports.test = test;
// --target es6
export function test() {
return new Promise(resolve => {
let a = {
a: 1,
b: 2
};
resolve(Object.assign({ c: 3 }, a));
});
}
// --target esnext
export function test() {
return new Promise(resolve => {
let a = {
a: 1,
b: 2
};
resolve({
c: 3,
...a
});
});
}
moduleResolution
Option
Type
Default
Desc
--moduleResolution
string
module === "AMD" or "System" or "ES6" ? "Classic" : "Node"
Determine how modules get resolved. Either "Node" for Node.js/io.js style resolution, or "Classic". See Module Resolution documentation for more details.
export function test() {
let a = {
a: 1
}
return {
b: 2,
...a
}
}
// --noEmitHelpers true
export function test() {
var a = {
a: 1
};
return __assign({ b: 2 }, a);
}
// --noEmitHelpers false
var __assign = (this && this.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
export function test() {
var a = {
a: 1
};
return __assign({ b: 2 }, a);
}
noEmitOnError
Option
Type
Default
Desc
--noEmitOnError
boolean
false
Do not emit outputs if any errors were reported.
编译有错误的时候,是否还生成文件。
noErrorTruncation
Option
Type
Default
Desc
--noEmitOnError
boolean
false
Do not truncate error messages.
不截断错误消息
noFallthroughCasesInSwitch
Option
Type
Default
Desc
----noFallthroughCasesInSwitch
boolean
false
Report errors for fallthrough cases in switch statement.
不允许swith中存在有内容的但没有break的case.
export let a = 1
switch(a) {
case 1:
console.log(a) // error TS7029: Fallthrough case in switch.
case 2:
}
noImplicitAny, noImplicitReturns, noImplicitThis and noImplicitUseStrict
Option
Type
Default
Desc
--noImplicitAny
boolean
false
Raise error on expressions and declarations with an implied any type.
--noImplicitReturns
boolean
false
Report error when not all code paths in function return a value.
--noImplicitThis
boolean
false
Raise error on this expressions with an implied any type.
--noImplicitUseStrict
boolean
false
Do not emit "use strict" directives in module output.
// --noImplicitAny true
function a1(b) { // error TS7006: Parameter 'b' implicitly has an 'any' type.
return b
}
// --noImplicitReturns true
function a2(b) { // 编译通过,与文档似乎不符
if (b) {
console.log(b)
return b
}
}
// --noImplicitThis true
function a1(b: any) { // error TS2683: 'this' implicitly has type 'any' because it does not have a type annotation.
return this.b
}
noLib
Option
Type
Default
Desc
--noLib
boolean
false
Do not include the default library file (lib.d.ts).
编译的时候不加载lib.d.ts.
那你还能编译?😂
noResolve
Option
Type
Default
Desc
--noResolve
boolean
false
Do not add triple-slash references or module import targets to the list of compiled files.
编译时,忽略///<reference path>和import引入的文件。
😂这种选项到底有啥用
// index.ts
/// <reference path="./my.d.ts" />
import { a } from './Test'
// my.d.ts
declare module A {
export function test(number, string): any
}
export function A() { // error TS6133: 'b' is declared but its value is never read.
let a = 0 // error TS6133: 'a' is declared but its value is never read.
return
}
outDir, outFile
Option
Type
Default
Desc
--outDir
string
Redirect output structure to the directory.
--outFile
string
Concatenate and emit output to single file. The order of concatenation is determined by the list of files passed to the compiler on the command line along with triple-slash references and imports. See output file order documentation for more details.
Stylize errors and messages using color and context.
对console上错误和消息做颜色和样式的美化处理。
project
Option
Type
Default
Desc
--project -p
string
Compile a project given a valid configuration file. The argument can be a file path to a valid JSON configuration file, or a directory path to a directory containing a tsconfig.json file. See tsconfig.json documentation for more details.
指定一个tsconfig.json文件
removeComments
Option
Type
Default
Desc
--removeComments
boolean
false
Remove all comments except copy-right header comments beginning with /*!
删除注释
rootDir
Option
Type
Default
Desc
--rootDir
string
Specifies the root directory of input files. Only use to control the output directory structure with --outDir.
Disable bivariant parameter checking for function types.
--strictPropertyInitialization
boolean
false
Enusre non-undefined class properties are initialized in the constructor.
--strictNullChecks
boolean
false
In strict null checking mode, the null and undefined values are not in the domain of every type and are only assignable to themselves and any (the one exception being that undefined is also assignable to void).
class A {
name: string
age = 10
constructor(age: number) { // error TS2564: Property 'name' has no initializer and is not definitely assigned in the constructor.
this.age = age
}
}
let a1: number = null // error TS2322: Type 'null' is not assignable to type 'number'.
let a2: string = undefined // error TS2322: Type 'undefined' is not assignable to type 'string'.
stripInternal
Option
Type
Default
Desc
--stripInternal
boolean
false
Do not emit declarations for code that has an /** @internal */ JSDoc annotation.
实验属性。不为有/** @internal */标记的代码生成declaration
suppressExcessPropertyErrors
Option
Type
Default
Desc
--suppressExcessPropertyErrors
boolean
false
Suppress excess property checks for object literals.
不对对象自变量的额外属性进行类型检测
export class A {
name: string
age = 10
constructor(age: number) {
this.age = age
}
}
let a: A = {
name: 'leon',
age: 30,
gender: 'male'
}
// --suppressExcessPropertyErrors false
error TS2322: Type '{ name: string; age: number; gender: string; }' is not assignable to type 'A'.
Object literal may only specify known properties, and 'gender' does not exist in type 'A'.
// --suppressExcessPropertyErrors true
pass
suppressImplicitAnyIndexErrors
Option
Type
Default
Desc
--suppressImplicitAnyIndexErrors
boolean
false
Suppress --noImplicitAny errors for indexing objects lacking index signatures. See issue #1232 for more details.
Module resolution kind is not specified, using 'NodeJs'.
Loading module as file / folder, candidate module location '/Users/leon/Documents/git/typescript-options/skipLibCheck/test', target file type'TypeScript'.
File '/Users/leon/Documents/git/typescript-options/skipLibCheck/test.ts' does not exist.
File '/Users/leon/Documents/git/typescript-options/skipLibCheck/test.tsx' does not exist.
File '/Users/leon/Documents/git/typescript-options/skipLibCheck/test.d.ts' exist - use it as a name resolution result.
types, typeRoots
Option
Type
Default
Desc
--types
string[]
List of names of type definitions to include. See @types, –typeRoots and –types for more details.
--typeRoots
string[]
List of folders to include type definitions from. See @types, –typeRoots and –types for more details.
typescript的编译选项一堆,微软爸爸写文档又马马虎虎 😂, 所以官方文档本身就不清不楚,似乎还有错误的地方。本文对各个选项进行实测,以期理解其含义以及每个选项会对编译或生成代码的影响。
typescript版本 2.7.2, 参考官方文档。
test code: https://github.com/njleonzhang/typescript-options
allowJs
是否会去编译
js
文件。allowJs设置为true的时候,生成的文件里会包含
leon.js
编译之后的版本,否则不会。allowSyntheticDefaultImports
直接翻译过来是:是否允许从没有default导出的模块中导入default。不影响代码的编译结果,只影响typechecking。
实际测试,似乎没什么作用. 可能我理解不对
allowUnreachableCode
无法到达的代码,是否报错。
allowUnusedLabels
无用的标签,是否报错
alwaysStrict
用严格模式来解析ts代码,并生成严格模式的js代码
关于严格模式参考MDN的文档
官方文档说默认值是false, 实测默认值是
true
baseUrl
解析非相对模块名的基准目录。查看模块解析文档了解详情。
charset
指定输入文件的编码方式。(一般指ts文件)
checkJs
和allowjs一起使用,js文件里有错误的时候,是否报错。
declaration 和 declarationDir
-d
declaration
指是否生成.d.ts
文件.declarationDir
指定生成的.d.ts
文件的目录diagnostics
显示诊断信息
设置为true的时候,会生成类似下面的诊断报告:
disableSizeLimit
禁用JavaScript工程体积大小的限制。
downlevelIteration
在生成目标代码为es5或者es3的时候,提供对 for..of, spread and destructuring语法的支持。
此选项为false时,转换为
此选项为true时,转换成:
emitBOM
生成的文件是否要带BOM头
esModuleInterop
生成的文件会为兼容babel而添加
__importStar
和__importDefault
的helper.这个选项会把
allowSyntheticDefaultImports
设置成true.加不加这个选项,都生成如下代码:
forceConsistentCasingInFileNames
是否在导入文件的时候需要保证大小写一致。
experimentalDecorators
启动实验的装饰器功能。
importHelpers
是否从tslib里导入__extends, __rest等helper函数
无论此项如何设置,始终会转换成:
inlineSourceMap
是否生成inline的source map
上栗中的代码,加本选项编译,文件末尾会多出sourcemap:
inlineSources
将代码与sourcemaps生成到一个文件中。
上栗中的代码,在加上此项进行编译,同样会在文件结尾加上sourceMappingURL,但生成的内容不同。暂时不太明白有什么实际上的区别。
isolatedModules
将每个文件当做一个独立的模块来转义
每个文件都需要是一个模块
另外次选项不能和
declaration
一起使用, 不太想的明白为什么 😂jsx
是否对jsx进行转换。一般不转译,把这个工作推迟给babel.
编译:
jsxFactory
编译:
lib
Possible values are:
►
ES5
►
ES6
►
ES2015
►
ES7
►
ES2016
►
ES2017
►
ESNext
►
DOM
►
DOM.Iterable
►
WebWorker
►
ScriptHost
►
ES2015.Core
►
ES2015.Collection
►
ES2015.Generator
►
ES2015.Iterable
►
ES2015.Promise
►
ES2015.Proxy
►
ES2015.Reflect
►
ES2015.Symbol
►
ES2015.Symbol.WellKnown
►
ES2016.Array.Include
►
ES2017.object
►
ES2017.SharedMemory
►
ES2017.TypedArrays
►
esnext.asynciterable
►
esnext.array
►
esnext.promise
Note: If
--lib
is not specified a default list of librares are injected. The default libraries injected are:► For
--target ES5
:DOM,ES5,ScriptHost
► For
--target ES6
:DOM,ES6,DOM.Iterable,ScriptHost
编译时,可以包括的库文件的列表。默认会inject一些库的定义。
会严重实际上是影响编译是否能成功。
listEmittedFiles
listEmittedFiles:列出编译生成文件
listFiles:列出参与编译的源文件
从例子我们也能看出
--lib
的作用locale
Possible values are:
► English (US):
en
► Czech:
cs
► German:
de
► Spanish:
es
► French:
fr
► Italian:
it
► Japanese:
ja
► Korean:
ko
► Polish:
pl
► Portuguese(Brazil):
pt-BR
► Russian:
ru
► Turkish:
tr
► Simplified Chinese:
zh-CN
► Traditional Chinese:
zh-TW
定义报错的message语言。
sourceMap, mapRoot 和 sourceRoot
sourceMap
: 生成sourceMapmapRoot
: 指定调试器去什么位置寻找map
文件. 当运行时.map
文件和对应的.js
文件不在同一位置时,需要使用本参数指定map
的位置. 指定的位置会被内嵌到sourceMap
中告诉调试器map
文件所在的位置.sourceRoot
: 指定调试器去什么位置寻找ts
文件. 当运行时.map
文件和对应的.js
文件不在同一位置时,需要使用本参数指定map
的位置. 指定的位置会被内嵌到sourceMap
中告诉调试器ts
文件所在的位置.maxNodeModuleJsDepth
去
node_modules
里搜索代码的层级, 默认是0.按照这个说法,似乎默认情况下不应该应许去加载
node_modules
目录下的文件。但是事实上,默认情况下,node_modules
下的模块是会被加载的。module
-m
"None"
,"CommonJS"
,"AMD"
,"System"
,"UMD"
,"ES6"
,"ES2015"
or"ESNext"
.► Only
"AMD"
and"System"
can be used in conjunction with--outFile
.►
"ES6"
and"ES2015"
values may be used when targeting"ES5"
or lower.指定生成代码的模块格式
target
-t
Note: "ESNext" targets latest supported ES proposed features.
指定目标代码的版本。
moduleResolution
定义typescript如何去查找module,详情查看官方说法
newLine
生成的代码里使用什么样的换行符
noEmit
noEmit: 不生成编译结果。
noEmitHelpers: 不生成helper函数. 设置为true,则
__assign
,__extends
等helper函数的实现,不会出现在生成的文件中。noEmitOnError
编译有错误的时候,是否还生成文件。
noErrorTruncation
不截断错误消息
noFallthroughCasesInSwitch
不允许swith中存在有内容的但没有break的case.
noImplicitAny, noImplicitReturns, noImplicitThis and noImplicitUseStrict
noImplicitAny 不允许使用隐式的使用
any
noImplicitReturns 不允许有隐式的return, 即所有分支都要显示的return。实测似乎无效。
noImplicitThis 不允许使用隐式的this,需要明确this的类型
noImplicitUseStrict 生成的文件中是否使用"use strict"。这TM和这选项的名字完全不是一个意思啊。为true的时候,生成的代码不会添加"use strict"
noLib
编译的时候不加载
lib.d.ts
.noResolve
编译时,忽略
///<reference path>
和import
引入的文件。noStrictGenericChecks
禁用严格的函数泛型检查。
noUnusedLocals, noUnusedParameters
noUnusedLocals: 不允许无用的临时变量
noUnusedParameters: 不允许未使用的参数
outDir, outFile
outDir: 把导出文件重定向到某个目录
outFile: 把所有的文件拼接并生成到单个文件中。
paths
只能用于tsconfig中,解析模块的时候的路径,地址是相对于baseUrl的。详情查看官方说法
preserveConstEnums
从生成的代码中擦除静态枚举的声明。
preserveSymlinks
不把符号链接解析为其真实路径;将符号链接文件视为真正的文件。
pretty
对console上错误和消息做颜色和样式的美化处理。
project
-p
指定一个
tsconfig.json
文件removeComments
删除注释
rootDir
指定输入文件的根目录,仅和outDir一起用于管理输出目录的结构。
rootDirs
指定多个根目录,并以此确定运行时的项目结构。
详见文档.
skipLibCheck
忽略所有的声明文件( *.d.ts)的类型检查。
加不加这个选项都会报错:
strict
Enabling
--strict
enables--noImplicitAny
,--noImplicitThis
,--alwaysStrict
,--strictNullChecks
,--strictFunctionTypes
and--strictPropertyInitialization
.开启一系列的强制检测。
strictFunctionTypes, strictPropertyInitialization, strictNullChecks
strictFunctionTypes
: 启用函数类型的严格检查。详见: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-6.htmlstrictPropertyInitialization
: 要求未定义的class成员变量,一定要在构造函数里进行初始化。strictNullChecks
:null
和undefined
, 不属于包含在其他任何类型,所以他们只能null
只能赋值给null
类型或any
类型,undefined
只能赋值给undefined
类型或者any
类型。但有一个例外:undefined
可以被赋值给void
类型stripInternal
实验属性。不为有
/** @internal */
标记的代码生成declarationsuppressExcessPropertyErrors
不对对象自变量的额外属性进行类型检测
suppressImplicitAnyIndexErrors
修复#1232的一个问题。
traceResolution
打印出module resolve过程的log。当moudle找不到的时候,可以打出log进行排查。
types, typeRoots
指定tyes文件列表和目录列表。
emitDecoratorMetadata
The text was updated successfully, but these errors were encountered: