From c89a80736e9d7e1ef7633f493a761414237f60ab Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Thu, 27 Dec 2018 19:46:21 +0900 Subject: [PATCH 001/149] add ES2019 target --- src/compiler/binder.ts | 2 +- src/compiler/commandLineParser.ts | 3 +- src/compiler/diagnosticMessages.json | 2 +- src/compiler/transformer.ts | 4 ++ src/compiler/transformers/es2019.ts | 37 ++++++++++++++ src/compiler/transformers/esnext.ts | 13 ----- src/compiler/tsconfig.json | 1 + src/compiler/types.ts | 51 ++++++++++--------- src/compiler/utilities.ts | 1 + .../unittests/config/commandLineParsing.ts | 2 +- .../config/convertCompilerOptionsFromJson.ts | 2 +- .../reference/api/tsserverlibrary.d.ts | 5 +- tests/baselines/reference/api/typescript.d.ts | 5 +- ...xt.js => emitter.noCatchBinding.es2019.js} | 7 +-- .../emitter.noCatchBinding.es2019.symbols | 11 ++++ ...es => emitter.noCatchBinding.es2019.types} | 3 +- .../emitter.noCatchBinding.esnext.symbols | 10 ---- .../tsconfig.json | 2 +- .../tsconfig.json | 2 +- .../tsconfig.json | 2 +- .../tsconfig.json | 2 +- .../tsconfig.json | 2 +- .../tsconfig.json | 2 +- .../tsconfig.json | 2 +- .../tsconfig.json | 2 +- .../tsconfig.json | 2 +- .../emitter.noCatchBinding.es2019.ts} | 4 +- 27 files changed, 110 insertions(+), 71 deletions(-) create mode 100644 src/compiler/transformers/es2019.ts rename tests/baselines/reference/{emitter.noCatchBinding.esnext.js => emitter.noCatchBinding.es2019.js} (73%) create mode 100644 tests/baselines/reference/emitter.noCatchBinding.es2019.symbols rename tests/baselines/reference/{emitter.noCatchBinding.esnext.types => emitter.noCatchBinding.es2019.types} (57%) delete mode 100644 tests/baselines/reference/emitter.noCatchBinding.esnext.symbols rename tests/cases/conformance/emitter/{esnext/noCatchBinding/emitter.noCatchBinding.esnext.ts => es2019/noCatchBinding/emitter.noCatchBinding.es2019.ts} (85%) diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 7216af4e817..79fef8b4e61 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -3259,7 +3259,7 @@ namespace ts { let transformFlags = subtreeFlags; if (!node.variableDeclaration) { - transformFlags |= TransformFlags.AssertESNext; + transformFlags |= TransformFlags.AssertES2019; } else if (isBindingPattern(node.variableDeclaration.name)) { transformFlags |= TransformFlags.AssertES2015; diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 43275605e23..053e09d48db 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -197,6 +197,7 @@ namespace ts { es2016: ScriptTarget.ES2016, es2017: ScriptTarget.ES2017, es2018: ScriptTarget.ES2018, + es2019: ScriptTarget.ES2019, esnext: ScriptTarget.ESNext, }), affectsSourceFile: true, @@ -204,7 +205,7 @@ namespace ts { paramType: Diagnostics.VERSION, showInSimplifiedHelpView: true, category: Diagnostics.Basic_Options, - description: Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_or_ESNEXT, + description: Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_or_ESNEXT, }, { name: "module", diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index b0dfb85ce6d..ee2d3532e50 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -3065,7 +3065,7 @@ "category": "Message", "code": 6014 }, - "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'.": { + "Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'.": { "category": "Message", "code": 6015 }, diff --git a/src/compiler/transformer.ts b/src/compiler/transformer.ts index fdcaadb4040..0d04b5667a9 100644 --- a/src/compiler/transformer.ts +++ b/src/compiler/transformer.ts @@ -42,6 +42,10 @@ namespace ts { transformers.push(transformESNext); } + if (languageVersion < ScriptTarget.ES2019) { + transformers.push(transformES2019); + } + if (languageVersion < ScriptTarget.ES2017) { transformers.push(transformES2017); } diff --git a/src/compiler/transformers/es2019.ts b/src/compiler/transformers/es2019.ts new file mode 100644 index 00000000000..7dfd17481eb --- /dev/null +++ b/src/compiler/transformers/es2019.ts @@ -0,0 +1,37 @@ +/*@internal*/ +namespace ts { + export function transformES2019(context: TransformationContext) { + return chainBundle(transformSourceFile); + + function transformSourceFile(node: SourceFile) { + if (node.isDeclarationFile) { + return node; + } + + return visitEachChild(node, visitor, context); + } + + function visitor(node: Node): VisitResult { + if ((node.transformFlags & TransformFlags.ContainsES2019) === 0) { + return node; + } + switch (node.kind) { + case SyntaxKind.CatchClause: + return visitCatchClause(node as CatchClause); + default: + return visitEachChild(node, visitor, context); + } + } + + function visitCatchClause(node: CatchClause): CatchClause { + if (!node.variableDeclaration) { + return updateCatchClause( + node, + createVariableDeclaration(createTempVariable(/*recordTempVariable*/ undefined)), + visitNode(node.block, visitor, isBlock) + ); + } + return visitEachChild(node, visitor, context); + } + } +} diff --git a/src/compiler/transformers/esnext.ts b/src/compiler/transformers/esnext.ts index cd62cca2c9d..a19396ec63c 100644 --- a/src/compiler/transformers/esnext.ts +++ b/src/compiler/transformers/esnext.ts @@ -105,8 +105,6 @@ namespace ts { return visitExpressionStatement(node as ExpressionStatement); case SyntaxKind.ParenthesizedExpression: return visitParenthesizedExpression(node as ParenthesizedExpression, noDestructuringValue); - case SyntaxKind.CatchClause: - return visitCatchClause(node as CatchClause); case SyntaxKind.PropertyAccessExpression: if (capturedSuperProperties && isPropertyAccessExpression(node) && node.expression.kind === SyntaxKind.SuperKeyword) { capturedSuperProperties.set(node.name.escapedText, true); @@ -249,17 +247,6 @@ namespace ts { return visitEachChild(node, noDestructuringValue ? visitorNoDestructuringValue : visitor, context); } - function visitCatchClause(node: CatchClause): CatchClause { - if (!node.variableDeclaration) { - return updateCatchClause( - node, - createVariableDeclaration(createTempVariable(/*recordTempVariable*/ undefined)), - visitNode(node.block, visitor, isBlock) - ); - } - return visitEachChild(node, visitor, context); - } - /** * Visits a BinaryExpression that contains a destructuring assignment. * diff --git a/src/compiler/tsconfig.json b/src/compiler/tsconfig.json index c41f47f3c4a..e5f6e9f83ba 100644 --- a/src/compiler/tsconfig.json +++ b/src/compiler/tsconfig.json @@ -30,6 +30,7 @@ "transformers/destructuring.ts", "transformers/ts.ts", "transformers/es2017.ts", + "transformers/es2019.ts", "transformers/esnext.ts", "transformers/jsx.ts", "transformers/es2016.ts", diff --git a/src/compiler/types.ts b/src/compiler/types.ts index b70b4e4d3d0..a4285cfd775 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -4646,7 +4646,8 @@ namespace ts { ES2016 = 3, ES2017 = 4, ES2018 = 5, - ESNext = 6, + ES2019 = 6, + ESNext = 7, JSON = 100, Latest = ESNext, } @@ -5034,32 +5035,33 @@ namespace ts { ContainsTypeScript = 1 << 1, ContainsJsx = 1 << 2, ContainsESNext = 1 << 3, - ContainsES2017 = 1 << 4, - ContainsES2016 = 1 << 5, - ES2015 = 1 << 6, - ContainsES2015 = 1 << 7, - Generator = 1 << 8, - ContainsGenerator = 1 << 9, - DestructuringAssignment = 1 << 10, - ContainsDestructuringAssignment = 1 << 11, + ContainsES2019 = 1 << 4, + ContainsES2017 = 1 << 5, + ContainsES2016 = 1 << 6, + ES2015 = 1 << 7, + ContainsES2015 = 1 << 8, + Generator = 1 << 9, + ContainsGenerator = 1 << 10, + DestructuringAssignment = 1 << 11, + ContainsDestructuringAssignment = 1 << 12, // Markers // - Flags used to indicate that a subtree contains a specific transformation. - ContainsTypeScriptClassSyntax = 1 << 12, // Decorators, Property Initializers, Parameter Property Initializers - ContainsLexicalThis = 1 << 13, - ContainsCapturedLexicalThis = 1 << 14, - ContainsLexicalThisInComputedPropertyName = 1 << 15, - ContainsDefaultValueAssignments = 1 << 16, - ContainsRestOrSpread = 1 << 17, - ContainsObjectRestOrSpread = 1 << 18, - ContainsComputedPropertyName = 1 << 19, - ContainsBlockScopedBinding = 1 << 20, - ContainsBindingPattern = 1 << 21, - ContainsYield = 1 << 22, - ContainsHoistedDeclarationOrCompletion = 1 << 23, - ContainsDynamicImport = 1 << 24, - Super = 1 << 25, - ContainsSuper = 1 << 26, + ContainsTypeScriptClassSyntax = 1 << 13, // Decorators, Property Initializers, Parameter Property Initializers + ContainsLexicalThis = 1 << 14, + ContainsCapturedLexicalThis = 1 << 15, + ContainsLexicalThisInComputedPropertyName = 1 << 16, + ContainsDefaultValueAssignments = 1 << 17, + ContainsRestOrSpread = 1 << 18, + ContainsObjectRestOrSpread = 1 << 19, + ContainsComputedPropertyName = 1 << 20, + ContainsBlockScopedBinding = 1 << 21, + ContainsBindingPattern = 1 << 22, + ContainsYield = 1 << 23, + ContainsHoistedDeclarationOrCompletion = 1 << 24, + ContainsDynamicImport = 1 << 25, + Super = 1 << 26, + ContainsSuper = 1 << 27, // Please leave this as 1 << 29. // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. @@ -5071,6 +5073,7 @@ namespace ts { AssertTypeScript = TypeScript | ContainsTypeScript, AssertJsx = ContainsJsx, AssertESNext = ContainsESNext, + AssertES2019 = ContainsES2019, AssertES2017 = ContainsES2017, AssertES2016 = ContainsES2016, AssertES2015 = ES2015 | ContainsES2015, diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 23c92216c56..357026d354f 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -4601,6 +4601,7 @@ namespace ts { switch (options.target) { case ScriptTarget.ESNext: return "lib.esnext.full.d.ts"; + case ScriptTarget.ES2019: case ScriptTarget.ES2018: return "lib.es2018.full.d.ts"; case ScriptTarget.ES2017: diff --git a/src/testRunner/unittests/config/commandLineParsing.ts b/src/testRunner/unittests/config/commandLineParsing.ts index 25fa3a45050..14639381a87 100644 --- a/src/testRunner/unittests/config/commandLineParsing.ts +++ b/src/testRunner/unittests/config/commandLineParsing.ts @@ -161,7 +161,7 @@ namespace ts { start: undefined, length: undefined, }, { - messageText: "Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es2015', 'es2016', 'es2017', 'es2018', 'esnext'.", + messageText: "Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es2015', 'es2016', 'es2017', 'es2018', 'es2019', 'esnext'.", category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, diff --git a/src/testRunner/unittests/config/convertCompilerOptionsFromJson.ts b/src/testRunner/unittests/config/convertCompilerOptionsFromJson.ts index 318bc0ceb26..e28acd241b7 100644 --- a/src/testRunner/unittests/config/convertCompilerOptionsFromJson.ts +++ b/src/testRunner/unittests/config/convertCompilerOptionsFromJson.ts @@ -238,7 +238,7 @@ namespace ts { file: undefined, start: 0, length: 0, - messageText: "Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es2015', 'es2016', 'es2017', 'es2018', 'esnext'.", + messageText: "Argument for '--target' option must be: 'es3', 'es5', 'es6', 'es2015', 'es2016', 'es2017', 'es2018', 'es2019', 'esnext'.", code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category }] diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 91f492ddd1d..d8ad3955edc 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -2566,9 +2566,10 @@ declare namespace ts { ES2016 = 3, ES2017 = 4, ES2018 = 5, - ESNext = 6, + ES2019 = 6, + ESNext = 7, JSON = 100, - Latest = 6 + Latest = 7 } enum LanguageVariant { Standard = 0, diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index 0e693f698f2..7465a4500cc 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -2566,9 +2566,10 @@ declare namespace ts { ES2016 = 3, ES2017 = 4, ES2018 = 5, - ESNext = 6, + ES2019 = 6, + ESNext = 7, JSON = 100, - Latest = 6 + Latest = 7 } enum LanguageVariant { Standard = 0, diff --git a/tests/baselines/reference/emitter.noCatchBinding.esnext.js b/tests/baselines/reference/emitter.noCatchBinding.es2019.js similarity index 73% rename from tests/baselines/reference/emitter.noCatchBinding.esnext.js rename to tests/baselines/reference/emitter.noCatchBinding.es2019.js index f47a947ca1a..c33657960de 100644 --- a/tests/baselines/reference/emitter.noCatchBinding.esnext.js +++ b/tests/baselines/reference/emitter.noCatchBinding.es2019.js @@ -1,13 +1,14 @@ -//// [emitter.noCatchBinding.esnext.ts] +//// [emitter.noCatchBinding.es2019.ts] function f() { try { } catch { } try { } catch { try { } catch { } } try { } catch { } finally { } -} +} -//// [emitter.noCatchBinding.esnext.js] + +//// [emitter.noCatchBinding.es2019.js] function f() { try { } catch { } diff --git a/tests/baselines/reference/emitter.noCatchBinding.es2019.symbols b/tests/baselines/reference/emitter.noCatchBinding.es2019.symbols new file mode 100644 index 00000000000..54dc63597d4 --- /dev/null +++ b/tests/baselines/reference/emitter.noCatchBinding.es2019.symbols @@ -0,0 +1,11 @@ +=== tests/cases/conformance/emitter/es2019/noCatchBinding/emitter.noCatchBinding.es2019.ts === +function f() { +>f : Symbol(f, Decl(emitter.noCatchBinding.es2019.ts, 0, 0)) + + try { } catch { } + try { } catch { + try { } catch { } + } + try { } catch { } finally { } +} + diff --git a/tests/baselines/reference/emitter.noCatchBinding.esnext.types b/tests/baselines/reference/emitter.noCatchBinding.es2019.types similarity index 57% rename from tests/baselines/reference/emitter.noCatchBinding.esnext.types rename to tests/baselines/reference/emitter.noCatchBinding.es2019.types index 70c2b728a5d..79647b35dc4 100644 --- a/tests/baselines/reference/emitter.noCatchBinding.esnext.types +++ b/tests/baselines/reference/emitter.noCatchBinding.es2019.types @@ -1,4 +1,4 @@ -=== tests/cases/conformance/emitter/esnext/noCatchBinding/emitter.noCatchBinding.esnext.ts === +=== tests/cases/conformance/emitter/es2019/noCatchBinding/emitter.noCatchBinding.es2019.ts === function f() { >f : () => void @@ -8,3 +8,4 @@ function f() { } try { } catch { } finally { } } + diff --git a/tests/baselines/reference/emitter.noCatchBinding.esnext.symbols b/tests/baselines/reference/emitter.noCatchBinding.esnext.symbols deleted file mode 100644 index 91242f5b01c..00000000000 --- a/tests/baselines/reference/emitter.noCatchBinding.esnext.symbols +++ /dev/null @@ -1,10 +0,0 @@ -=== tests/cases/conformance/emitter/esnext/noCatchBinding/emitter.noCatchBinding.esnext.ts === -function f() { ->f : Symbol(f, Decl(emitter.noCatchBinding.esnext.ts, 0, 0)) - - try { } catch { } - try { } catch { - try { } catch { } - } - try { } catch { } finally { } -} diff --git a/tests/baselines/reference/tsConfig/Default initialized TSConfig/tsconfig.json b/tests/baselines/reference/tsConfig/Default initialized TSConfig/tsconfig.json index ac5ebf02160..b7f98718a83 100644 --- a/tests/baselines/reference/tsConfig/Default initialized TSConfig/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Default initialized TSConfig/tsconfig.json @@ -1,7 +1,7 @@ { "compilerOptions": { /* Basic Options */ - "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */ + "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */ "module": "commonjs", /* 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. */ diff --git a/tests/baselines/reference/tsConfig/Initialized TSConfig with advanced options/tsconfig.json b/tests/baselines/reference/tsConfig/Initialized TSConfig with advanced options/tsconfig.json index 0e4adce88d2..452ec708540 100644 --- a/tests/baselines/reference/tsConfig/Initialized TSConfig with advanced options/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Initialized TSConfig with advanced options/tsconfig.json @@ -1,7 +1,7 @@ { "compilerOptions": { /* Basic Options */ - "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */ + "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */ "module": "commonjs", /* 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. */ diff --git a/tests/baselines/reference/tsConfig/Initialized TSConfig with boolean value compiler options/tsconfig.json b/tests/baselines/reference/tsConfig/Initialized TSConfig with boolean value compiler options/tsconfig.json index 211bcb97d5f..edd4a72bd8a 100644 --- a/tests/baselines/reference/tsConfig/Initialized TSConfig with boolean value compiler options/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Initialized TSConfig with boolean value compiler options/tsconfig.json @@ -1,7 +1,7 @@ { "compilerOptions": { /* Basic Options */ - "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */ + "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */ "module": "commonjs", /* 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. */ diff --git a/tests/baselines/reference/tsConfig/Initialized TSConfig with enum value compiler options/tsconfig.json b/tests/baselines/reference/tsConfig/Initialized TSConfig with enum value compiler options/tsconfig.json index 8c3d7be38ec..d6edb9d5c68 100644 --- a/tests/baselines/reference/tsConfig/Initialized TSConfig with enum value compiler options/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Initialized TSConfig with enum value compiler options/tsconfig.json @@ -1,7 +1,7 @@ { "compilerOptions": { /* Basic Options */ - "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */ + "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */ "module": "commonjs", /* 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. */ diff --git a/tests/baselines/reference/tsConfig/Initialized TSConfig with files options/tsconfig.json b/tests/baselines/reference/tsConfig/Initialized TSConfig with files options/tsconfig.json index b8dfce1ff43..ad38b2ad884 100644 --- a/tests/baselines/reference/tsConfig/Initialized TSConfig with files options/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Initialized TSConfig with files options/tsconfig.json @@ -1,7 +1,7 @@ { "compilerOptions": { /* Basic Options */ - "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */ + "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */ "module": "commonjs", /* 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. */ diff --git a/tests/baselines/reference/tsConfig/Initialized TSConfig with incorrect compiler option value/tsconfig.json b/tests/baselines/reference/tsConfig/Initialized TSConfig with incorrect compiler option value/tsconfig.json index 60cccb8b3b3..b0107d9d742 100644 --- a/tests/baselines/reference/tsConfig/Initialized TSConfig with incorrect compiler option value/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Initialized TSConfig with incorrect compiler option value/tsconfig.json @@ -1,7 +1,7 @@ { "compilerOptions": { /* Basic Options */ - "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */ + "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */ "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ "lib": ["es5","es2015.promise"], /* Specify library files to be included in the compilation. */ // "allowJs": true, /* Allow javascript files to be compiled. */ diff --git a/tests/baselines/reference/tsConfig/Initialized TSConfig with incorrect compiler option/tsconfig.json b/tests/baselines/reference/tsConfig/Initialized TSConfig with incorrect compiler option/tsconfig.json index ac5ebf02160..b7f98718a83 100644 --- a/tests/baselines/reference/tsConfig/Initialized TSConfig with incorrect compiler option/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Initialized TSConfig with incorrect compiler option/tsconfig.json @@ -1,7 +1,7 @@ { "compilerOptions": { /* Basic Options */ - "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */ + "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */ "module": "commonjs", /* 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. */ diff --git a/tests/baselines/reference/tsConfig/Initialized TSConfig with list compiler options with enum value/tsconfig.json b/tests/baselines/reference/tsConfig/Initialized TSConfig with list compiler options with enum value/tsconfig.json index 81641589d59..8263ed18aae 100644 --- a/tests/baselines/reference/tsConfig/Initialized TSConfig with list compiler options with enum value/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Initialized TSConfig with list compiler options with enum value/tsconfig.json @@ -1,7 +1,7 @@ { "compilerOptions": { /* Basic Options */ - "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */ + "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */ "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ "lib": ["es5","es2015.core"], /* Specify library files to be included in the compilation. */ // "allowJs": true, /* Allow javascript files to be compiled. */ diff --git a/tests/baselines/reference/tsConfig/Initialized TSConfig with list compiler options/tsconfig.json b/tests/baselines/reference/tsConfig/Initialized TSConfig with list compiler options/tsconfig.json index 826babfd625..69249714660 100644 --- a/tests/baselines/reference/tsConfig/Initialized TSConfig with list compiler options/tsconfig.json +++ b/tests/baselines/reference/tsConfig/Initialized TSConfig with list compiler options/tsconfig.json @@ -1,7 +1,7 @@ { "compilerOptions": { /* Basic Options */ - "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */ + "target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */ "module": "commonjs", /* 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. */ diff --git a/tests/cases/conformance/emitter/esnext/noCatchBinding/emitter.noCatchBinding.esnext.ts b/tests/cases/conformance/emitter/es2019/noCatchBinding/emitter.noCatchBinding.es2019.ts similarity index 85% rename from tests/cases/conformance/emitter/esnext/noCatchBinding/emitter.noCatchBinding.esnext.ts rename to tests/cases/conformance/emitter/es2019/noCatchBinding/emitter.noCatchBinding.es2019.ts index 8e87b3c8c8f..d9dfb1bcd9a 100644 --- a/tests/cases/conformance/emitter/esnext/noCatchBinding/emitter.noCatchBinding.esnext.ts +++ b/tests/cases/conformance/emitter/es2019/noCatchBinding/emitter.noCatchBinding.es2019.ts @@ -1,8 +1,8 @@ -// @target: esnext +// @target: es2019 function f() { try { } catch { } try { } catch { try { } catch { } } try { } catch { } finally { } -} \ No newline at end of file +} From 1d8a2ea38c301f3ddda39aa4bdae8fe6d7c33ffe Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Sun, 6 Jan 2019 11:42:55 +0900 Subject: [PATCH 002/149] Symbol.prototype.description hit stage 4 --- src/compiler/commandLineParser.ts | 3 ++- src/compiler/utilities.ts | 1 + src/lib/es2019.d.ts | 2 ++ src/lib/es2019.full.d.ts | 5 +++++ .../{esnext.symbol.d.ts => es2019.symbol.d.ts} | 0 src/lib/esnext.d.ts | 3 +-- src/lib/libs.json | 4 +++- .../unittests/config/commandLineParsing.ts | 6 +++--- tests/baselines/reference/bigintIndex.symbols | 2 +- tests/baselines/reference/dynamicNames.symbols | 2 +- .../reference/dynamicNamesErrors.symbols | 8 ++++---- .../objectLiteralPropertyImplicitlyAny.symbols | 2 +- .../unionTypeWithIndexSignature.symbols | 2 +- .../baselines/reference/uniqueSymbols.symbols | 18 +++++++++--------- .../uniqueSymbolsDeclarations.symbols | 18 +++++++++--------- .../reference/uniqueSymbolsErrors.symbols | 2 +- 16 files changed, 44 insertions(+), 34 deletions(-) create mode 100644 src/lib/es2019.d.ts create mode 100644 src/lib/es2019.full.d.ts rename src/lib/{esnext.symbol.d.ts => es2019.symbol.d.ts} (100%) diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 053e09d48db..69f829d0379 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -15,6 +15,7 @@ namespace ts { ["es2016", "lib.es2016.d.ts"], ["es2017", "lib.es2017.d.ts"], ["es2018", "lib.es2018.d.ts"], + ["es2019", "lib.es2019.d.ts"], ["esnext", "lib.esnext.d.ts"], // Host only ["dom", "lib.dom.d.ts"], @@ -41,8 +42,8 @@ namespace ts { ["es2018.intl", "lib.es2018.intl.d.ts"], ["es2018.promise", "lib.es2018.promise.d.ts"], ["es2018.regexp", "lib.es2018.regexp.d.ts"], + ["es2019.symbol", "lib.es2019.symbol.d.ts"], ["esnext.array", "lib.esnext.array.d.ts"], - ["esnext.symbol", "lib.esnext.symbol.d.ts"], ["esnext.asynciterable", "lib.esnext.asynciterable.d.ts"], ["esnext.intl", "lib.esnext.intl.d.ts"], ["esnext.bigint", "lib.esnext.bigint.d.ts"] diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 357026d354f..ca83129bb3f 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -4602,6 +4602,7 @@ namespace ts { case ScriptTarget.ESNext: return "lib.esnext.full.d.ts"; case ScriptTarget.ES2019: + return "lib.es2019.full.d.ts"; case ScriptTarget.ES2018: return "lib.es2018.full.d.ts"; case ScriptTarget.ES2017: diff --git a/src/lib/es2019.d.ts b/src/lib/es2019.d.ts new file mode 100644 index 00000000000..60b8787d587 --- /dev/null +++ b/src/lib/es2019.d.ts @@ -0,0 +1,2 @@ +/// +/// diff --git a/src/lib/es2019.full.d.ts b/src/lib/es2019.full.d.ts new file mode 100644 index 00000000000..2056578133e --- /dev/null +++ b/src/lib/es2019.full.d.ts @@ -0,0 +1,5 @@ +/// +/// +/// +/// +/// diff --git a/src/lib/esnext.symbol.d.ts b/src/lib/es2019.symbol.d.ts similarity index 100% rename from src/lib/esnext.symbol.d.ts rename to src/lib/es2019.symbol.d.ts diff --git a/src/lib/esnext.d.ts b/src/lib/esnext.d.ts index 45d7e1d96c9..6e73347bf3a 100644 --- a/src/lib/esnext.d.ts +++ b/src/lib/esnext.d.ts @@ -1,6 +1,5 @@ -/// +/// /// /// /// -/// /// diff --git a/src/lib/libs.json b/src/lib/libs.json index 3077181af6e..17b54324e9d 100644 --- a/src/lib/libs.json +++ b/src/lib/libs.json @@ -6,6 +6,7 @@ "es2016", "es2017", "es2018", + "es2019", "esnext", // Host only "dom.generated", @@ -32,10 +33,10 @@ "es2018.regexp", "es2018.promise", "es2018.intl", + "es2019.symbol", "esnext.asynciterable", "esnext.array", "esnext.bigint", - "esnext.symbol", "esnext.intl", // Default libraries "es5.full", @@ -43,6 +44,7 @@ "es2016.full", "es2017.full", "es2018.full", + "es2019.full", "esnext.full" ], "paths": { diff --git a/src/testRunner/unittests/config/commandLineParsing.ts b/src/testRunner/unittests/config/commandLineParsing.ts index 14639381a87..8d49fde6e42 100644 --- a/src/testRunner/unittests/config/commandLineParsing.ts +++ b/src/testRunner/unittests/config/commandLineParsing.ts @@ -57,7 +57,7 @@ namespace ts { assertParseResult(["--lib", "es5,invalidOption", "0.ts"], { errors: [{ - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', '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.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', '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.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.symbol', 'esnext.array', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.", category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, file: undefined, @@ -259,7 +259,7 @@ namespace ts { assertParseResult(["--lib", "es5,", "es7", "0.ts"], { errors: [{ - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', '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.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', '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.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.symbol', 'esnext.array', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.", category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, file: undefined, @@ -278,7 +278,7 @@ namespace ts { assertParseResult(["--lib", "es5, ", "es7", "0.ts"], { errors: [{ - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', '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.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', '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.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.symbol', 'esnext.array', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.", category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, file: undefined, diff --git a/tests/baselines/reference/bigintIndex.symbols b/tests/baselines/reference/bigintIndex.symbols index c115a0f9daf..c0aea092753 100644 --- a/tests/baselines/reference/bigintIndex.symbols +++ b/tests/baselines/reference/bigintIndex.symbols @@ -34,7 +34,7 @@ key = "abc"; key = Symbol(); >key : Symbol(key, Decl(a.ts, 9, 3)) ->Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.esnext.symbol.d.ts, --, --)) +>Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2019.symbol.d.ts, --, --)) key = 123n; // should error >key : Symbol(key, Decl(a.ts, 9, 3)) diff --git a/tests/baselines/reference/dynamicNames.symbols b/tests/baselines/reference/dynamicNames.symbols index cfed2817d1d..08f7be94fd5 100644 --- a/tests/baselines/reference/dynamicNames.symbols +++ b/tests/baselines/reference/dynamicNames.symbols @@ -7,7 +7,7 @@ export const c1 = 1; export const s0 = Symbol(); >s0 : Symbol(s0, Decl(module.ts, 2, 12)) ->Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.esnext.symbol.d.ts, --, --)) +>Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2019.symbol.d.ts, --, --)) export interface T0 { >T0 : Symbol(T0, Decl(module.ts, 2, 27)) diff --git a/tests/baselines/reference/dynamicNamesErrors.symbols b/tests/baselines/reference/dynamicNamesErrors.symbols index de0d98df453..95fa0cd751e 100644 --- a/tests/baselines/reference/dynamicNamesErrors.symbols +++ b/tests/baselines/reference/dynamicNamesErrors.symbols @@ -62,19 +62,19 @@ t2 = t1; const x = Symbol(); >x : Symbol(x, Decl(dynamicNamesErrors.ts, 26, 5)) ->Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.esnext.symbol.d.ts, --, --)) +>Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2019.symbol.d.ts, --, --)) const y = Symbol(); >y : Symbol(y, Decl(dynamicNamesErrors.ts, 27, 5)) ->Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.esnext.symbol.d.ts, --, --)) +>Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2019.symbol.d.ts, --, --)) const z = Symbol(); >z : Symbol(z, Decl(dynamicNamesErrors.ts, 28, 5)) ->Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.esnext.symbol.d.ts, --, --)) +>Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2019.symbol.d.ts, --, --)) const w = Symbol(); >w : Symbol(w, Decl(dynamicNamesErrors.ts, 29, 5)) ->Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.esnext.symbol.d.ts, --, --)) +>Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2019.symbol.d.ts, --, --)) export interface InterfaceMemberVisibility { >InterfaceMemberVisibility : Symbol(InterfaceMemberVisibility, Decl(dynamicNamesErrors.ts, 29, 19)) diff --git a/tests/baselines/reference/objectLiteralPropertyImplicitlyAny.symbols b/tests/baselines/reference/objectLiteralPropertyImplicitlyAny.symbols index ae29ff8bb9e..7f61190b91f 100644 --- a/tests/baselines/reference/objectLiteralPropertyImplicitlyAny.symbols +++ b/tests/baselines/reference/objectLiteralPropertyImplicitlyAny.symbols @@ -2,7 +2,7 @@ const foo = Symbol.for("foo"); >foo : Symbol(foo, Decl(objectLiteralPropertyImplicitlyAny.ts, 0, 5)) >Symbol.for : Symbol(SymbolConstructor.for, Decl(lib.es2015.symbol.d.ts, --, --)) ->Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.esnext.symbol.d.ts, --, --)) +>Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2019.symbol.d.ts, --, --)) >for : Symbol(SymbolConstructor.for, Decl(lib.es2015.symbol.d.ts, --, --)) const o = { [foo]: undefined }; diff --git a/tests/baselines/reference/unionTypeWithIndexSignature.symbols b/tests/baselines/reference/unionTypeWithIndexSignature.symbols index b207423057b..8d38cbb6403 100644 --- a/tests/baselines/reference/unionTypeWithIndexSignature.symbols +++ b/tests/baselines/reference/unionTypeWithIndexSignature.symbols @@ -87,7 +87,7 @@ num['0'] = 'ok' const sym = Symbol() >sym : Symbol(sym, Decl(unionTypeWithIndexSignature.ts, 18, 5)) ->Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.esnext.symbol.d.ts, --, --)) +>Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2019.symbol.d.ts, --, --)) type Both = { s: number, '0': number, [sym]: boolean } | { [n: number]: number, [s: string]: string | number } >Both : Symbol(Both, Decl(unionTypeWithIndexSignature.ts, 18, 20)) diff --git a/tests/baselines/reference/uniqueSymbols.symbols b/tests/baselines/reference/uniqueSymbols.symbols index 6fef1873082..af2cfa74f82 100644 --- a/tests/baselines/reference/uniqueSymbols.symbols +++ b/tests/baselines/reference/uniqueSymbols.symbols @@ -2,15 +2,15 @@ // declarations with call initializer const constCall = Symbol(); >constCall : Symbol(constCall, Decl(uniqueSymbols.ts, 1, 5)) ->Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.esnext.symbol.d.ts, --, --)) +>Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2019.symbol.d.ts, --, --)) let letCall = Symbol(); >letCall : Symbol(letCall, Decl(uniqueSymbols.ts, 2, 3)) ->Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.esnext.symbol.d.ts, --, --)) +>Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2019.symbol.d.ts, --, --)) var varCall = Symbol(); >varCall : Symbol(varCall, Decl(uniqueSymbols.ts, 3, 3)) ->Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.esnext.symbol.d.ts, --, --)) +>Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2019.symbol.d.ts, --, --)) // ambient declaration with type declare const constType: unique symbol; @@ -19,7 +19,7 @@ declare const constType: unique symbol; // declaration with type and call initializer const constTypeAndCall: unique symbol = Symbol(); >constTypeAndCall : Symbol(constTypeAndCall, Decl(uniqueSymbols.ts, 9, 5)) ->Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.esnext.symbol.d.ts, --, --)) +>Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2019.symbol.d.ts, --, --)) // declaration from initializer const constInitToConstCall = constCall; @@ -152,26 +152,26 @@ class C { static readonly readonlyStaticCall = Symbol(); >readonlyStaticCall : Symbol(C.readonlyStaticCall, Decl(uniqueSymbols.ts, 56, 9)) ->Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.esnext.symbol.d.ts, --, --)) +>Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2019.symbol.d.ts, --, --)) static readonly readonlyStaticType: unique symbol; >readonlyStaticType : Symbol(C.readonlyStaticType, Decl(uniqueSymbols.ts, 57, 50)) static readonly readonlyStaticTypeAndCall: unique symbol = Symbol(); >readonlyStaticTypeAndCall : Symbol(C.readonlyStaticTypeAndCall, Decl(uniqueSymbols.ts, 58, 54)) ->Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.esnext.symbol.d.ts, --, --)) +>Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2019.symbol.d.ts, --, --)) static readwriteStaticCall = Symbol(); >readwriteStaticCall : Symbol(C.readwriteStaticCall, Decl(uniqueSymbols.ts, 59, 72)) ->Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.esnext.symbol.d.ts, --, --)) +>Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2019.symbol.d.ts, --, --)) readonly readonlyCall = Symbol(); >readonlyCall : Symbol(C.readonlyCall, Decl(uniqueSymbols.ts, 60, 42)) ->Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.esnext.symbol.d.ts, --, --)) +>Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2019.symbol.d.ts, --, --)) readwriteCall = Symbol(); >readwriteCall : Symbol(C.readwriteCall, Decl(uniqueSymbols.ts, 62, 37)) ->Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.esnext.symbol.d.ts, --, --)) +>Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2019.symbol.d.ts, --, --)) } declare const c: C; >c : Symbol(c, Decl(uniqueSymbols.ts, 65, 13)) diff --git a/tests/baselines/reference/uniqueSymbolsDeclarations.symbols b/tests/baselines/reference/uniqueSymbolsDeclarations.symbols index 485b31af0fd..6e3ae6d6a46 100644 --- a/tests/baselines/reference/uniqueSymbolsDeclarations.symbols +++ b/tests/baselines/reference/uniqueSymbolsDeclarations.symbols @@ -2,15 +2,15 @@ // declarations with call initializer const constCall = Symbol(); >constCall : Symbol(constCall, Decl(uniqueSymbolsDeclarations.ts, 1, 5)) ->Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.esnext.symbol.d.ts, --, --)) +>Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2019.symbol.d.ts, --, --)) let letCall = Symbol(); >letCall : Symbol(letCall, Decl(uniqueSymbolsDeclarations.ts, 2, 3)) ->Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.esnext.symbol.d.ts, --, --)) +>Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2019.symbol.d.ts, --, --)) var varCall = Symbol(); >varCall : Symbol(varCall, Decl(uniqueSymbolsDeclarations.ts, 3, 3)) ->Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.esnext.symbol.d.ts, --, --)) +>Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2019.symbol.d.ts, --, --)) // ambient declaration with type declare const constType: unique symbol; @@ -19,7 +19,7 @@ declare const constType: unique symbol; // declaration with type and call initializer const constTypeAndCall: unique symbol = Symbol(); >constTypeAndCall : Symbol(constTypeAndCall, Decl(uniqueSymbolsDeclarations.ts, 9, 5)) ->Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.esnext.symbol.d.ts, --, --)) +>Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2019.symbol.d.ts, --, --)) // declaration from initializer const constInitToConstCall = constCall; @@ -152,26 +152,26 @@ class C { static readonly readonlyStaticCall = Symbol(); >readonlyStaticCall : Symbol(C.readonlyStaticCall, Decl(uniqueSymbolsDeclarations.ts, 56, 9)) ->Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.esnext.symbol.d.ts, --, --)) +>Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2019.symbol.d.ts, --, --)) static readonly readonlyStaticType: unique symbol; >readonlyStaticType : Symbol(C.readonlyStaticType, Decl(uniqueSymbolsDeclarations.ts, 57, 50)) static readonly readonlyStaticTypeAndCall: unique symbol = Symbol(); >readonlyStaticTypeAndCall : Symbol(C.readonlyStaticTypeAndCall, Decl(uniqueSymbolsDeclarations.ts, 58, 54)) ->Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.esnext.symbol.d.ts, --, --)) +>Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2019.symbol.d.ts, --, --)) static readwriteStaticCall = Symbol(); >readwriteStaticCall : Symbol(C.readwriteStaticCall, Decl(uniqueSymbolsDeclarations.ts, 59, 72)) ->Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.esnext.symbol.d.ts, --, --)) +>Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2019.symbol.d.ts, --, --)) readonly readonlyCall = Symbol(); >readonlyCall : Symbol(C.readonlyCall, Decl(uniqueSymbolsDeclarations.ts, 60, 42)) ->Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.esnext.symbol.d.ts, --, --)) +>Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2019.symbol.d.ts, --, --)) readwriteCall = Symbol(); >readwriteCall : Symbol(C.readwriteCall, Decl(uniqueSymbolsDeclarations.ts, 62, 37)) ->Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.esnext.symbol.d.ts, --, --)) +>Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2019.symbol.d.ts, --, --)) } declare const c: C; >c : Symbol(c, Decl(uniqueSymbolsDeclarations.ts, 65, 13)) diff --git a/tests/baselines/reference/uniqueSymbolsErrors.symbols b/tests/baselines/reference/uniqueSymbolsErrors.symbols index affcd6f096b..2e2b552225a 100644 --- a/tests/baselines/reference/uniqueSymbolsErrors.symbols +++ b/tests/baselines/reference/uniqueSymbolsErrors.symbols @@ -238,5 +238,5 @@ declare const invalidIntersection: unique symbol | unique symbol; // https://github.com/Microsoft/TypeScript/issues/21584 const shouldNotBeAssignable: string = Symbol(); >shouldNotBeAssignable : Symbol(shouldNotBeAssignable, Decl(uniqueSymbolsErrors.ts, 86, 5)) ->Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.esnext.symbol.d.ts, --, --)) +>Symbol : Symbol(Symbol, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.symbol.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2019.symbol.d.ts, --, --)) From 9aeeae54b0af3942a4ba24eeb4cb8ab60e513cfc Mon Sep 17 00:00:00 2001 From: Gabriela Britto Date: Tue, 15 Jan 2019 16:56:53 -0800 Subject: [PATCH 003/149] create refactoring for converting to named parameters --- .../refactors/convertToNamedParameters.ts | 94 +++++++++++++++++++ src/services/tsconfig.json | 1 + 2 files changed, 95 insertions(+) create mode 100644 src/services/refactors/convertToNamedParameters.ts diff --git a/src/services/refactors/convertToNamedParameters.ts b/src/services/refactors/convertToNamedParameters.ts new file mode 100644 index 00000000000..dd4e4326737 --- /dev/null +++ b/src/services/refactors/convertToNamedParameters.ts @@ -0,0 +1,94 @@ +/* @internal */ +namespace ts.refactor.convertToNamedParameters { + const refactorName = "Convert to named parameters"; + const refactorDescription = "Convert to named parameters"; + const actionNameNamedParameters = "Convert to named parameters"; + const actionDescriptionNamedParameters = "Convert to named parameters"; + const minimumParameterLength = 3; + const paramTypeNamePostfix = "Param"; + registerRefactor(refactorName, { getEditsForAction, getAvailableActions }); + + + function getAvailableActions(context: RefactorContext): ReadonlyArray { + const { file, startPosition } = context; + const func = getFunctionDeclarationAtPosition(file, startPosition); + if (!func) return emptyArray; + + return [{ + name: refactorName, + description: refactorDescription, + actions: [{ + name: actionNameNamedParameters, + description: actionDescriptionNamedParameters + }] + }]; + } + + function getEditsForAction(context: RefactorContext, actionName: string): RefactorEditInfo | undefined { + Debug.assert(actionName === actionNameNamedParameters); + const { file, startPosition } = context; + const func = getFunctionDeclarationAtPosition(file, startPosition); + if (!func) return undefined; + + const paramTypeDeclaration = createParamTypeDeclaration(func); + return undefined; + } + + function getFunctionDeclarationAtPosition(file: SourceFile, startPosition: number): ValidFunctionDeclaration | undefined { + const node = getTokenAtPosition(file, startPosition); + const func = getContainingFunction(node); + if (!func || !isValidFunctionDeclaration(func)) return undefined; + return func; + } + + function isValidFunctionDeclaration(func: SignatureDeclaration): func is ValidFunctionDeclaration { + switch (func.kind) { + case SyntaxKind.FunctionDeclaration: + case SyntaxKind.MethodDeclaration: + if (func.name && func.parameters && func.parameters.length > minimumParameterLength) { + return true; + } + break; + default: + } + return false; + } + + function createParamTypeDeclaration(func: ValidFunctionDeclaration): InterfaceDeclaration { + const paramTypeName = getFunctionName(func); + const paramTypeMembers = + ts.map(func.parameters, + (paramDecl, _i) => createPropertySignatureFromParameterDeclaration(paramDecl)); + return createInterfaceDeclaration( + /* decorators */ undefined, + /* modifiers */ undefined, + createIdentifier(paramTypeName), + /* type parameters */ undefined, + /* heritage clauses */ undefined, + createNodeArray(paramTypeMembers)); + } + + function getFunctionName(func: ValidFunctionDeclaration): string { + return entityNameToString(func.name) + paramTypeNamePostfix; + } + + function createPropertySignatureFromParameterDeclaration(paramDeclaration: ValidParameterDeclaration): PropertySignature { + return createPropertySignature( + /*modifiers*/ undefined, + paramDeclaration.name, + paramDeclaration.questionToken, + paramDeclaration.type, + paramDeclaration.initializer); + } + + interface ValidFunctionDeclaration extends FunctionDeclaration { + name: Identifier; + body?: FunctionBody; + typeParameters?: NodeArray; + parameters: NodeArray; + } + + interface ValidParameterDeclaration extends ParameterDeclaration { + name: Identifier; + } +} \ No newline at end of file diff --git a/src/services/tsconfig.json b/src/services/tsconfig.json index 21be663055a..793089e62c8 100644 --- a/src/services/tsconfig.json +++ b/src/services/tsconfig.json @@ -84,6 +84,7 @@ "refactors/generateGetAccessorAndSetAccessor.ts", "refactors/moveToNewFile.ts", "refactors/addOrRemoveBracesToArrowFunction.ts", + "refactors/convertToNamedParameters.ts", "services.ts", "breakpoints.ts", "transform.ts", From 705ac60a592a98a09a564e1f78e9af8173cc966e Mon Sep 17 00:00:00 2001 From: Gabriela Britto Date: Wed, 16 Jan 2019 15:49:09 -0800 Subject: [PATCH 004/149] WIP --- .../refactors/convertToNamedParameters.ts | 50 ++++++++++++++----- 1 file changed, 37 insertions(+), 13 deletions(-) diff --git a/src/services/refactors/convertToNamedParameters.ts b/src/services/refactors/convertToNamedParameters.ts index dd4e4326737..0b5d3d265ff 100644 --- a/src/services/refactors/convertToNamedParameters.ts +++ b/src/services/refactors/convertToNamedParameters.ts @@ -31,7 +31,9 @@ namespace ts.refactor.convertToNamedParameters { if (!func) return undefined; const paramTypeDeclaration = createParamTypeDeclaration(func); - return undefined; + const edits = textChanges.ChangeTracker.with(context, t => t.replaceNode(file, func, paramTypeDeclaration)); + // return undefined; + return { renameFilename: undefined, renameLocation: undefined, edits }; } function getFunctionDeclarationAtPosition(file: SourceFile, startPosition: number): ValidFunctionDeclaration | undefined { @@ -45,31 +47,36 @@ namespace ts.refactor.convertToNamedParameters { switch (func.kind) { case SyntaxKind.FunctionDeclaration: case SyntaxKind.MethodDeclaration: - if (func.name && func.parameters && func.parameters.length > minimumParameterLength) { - return true; - } - break; + case SyntaxKind.Constructor: + return !!(func.name && isValidParameterNodeArray(func.parameters)); default: } return false; } + function isValidParameterNodeArray(parameters: NodeArray): boolean { + return parameters && parameters.length > minimumParameterLength && ts.every(parameters, isValidParameterDeclaration); + } + + function isValidParameterDeclaration(paramDecl: ParameterDeclaration): paramDecl is ValidParameterDeclaration { + return !paramDecl.modifiers && !paramDecl.dotDotDotToken && isIdentifier(paramDecl.name) && !paramDecl.initializer; + } + function createParamTypeDeclaration(func: ValidFunctionDeclaration): InterfaceDeclaration { const paramTypeName = getFunctionName(func); - const paramTypeMembers = - ts.map(func.parameters, - (paramDecl, _i) => createPropertySignatureFromParameterDeclaration(paramDecl)); + const paramTypeMembers = ts.map(func.parameters, createPropertySignatureFromParameterDeclaration); + return createInterfaceDeclaration( /* decorators */ undefined, /* modifiers */ undefined, createIdentifier(paramTypeName), - /* type parameters */ undefined, - /* heritage clauses */ undefined, + func.typeParameters, + /* heritageClauses */ undefined, createNodeArray(paramTypeMembers)); } function getFunctionName(func: ValidFunctionDeclaration): string { - return entityNameToString(func.name) + paramTypeNamePostfix; + return declarationNameToString(func.name) + paramTypeNamePostfix; } function createPropertySignatureFromParameterDeclaration(paramDeclaration: ValidParameterDeclaration): PropertySignature { @@ -81,8 +88,21 @@ namespace ts.refactor.convertToNamedParameters { paramDeclaration.initializer); } - interface ValidFunctionDeclaration extends FunctionDeclaration { - name: Identifier; + function createParameterObjectBindingPattern(parameters: NodeArray, paramType: TypeNode): ParameterDeclaration { + const bindingElements = ts.map(parameters, param => createBindingElement(/* dotDotDotToken */ undefined, /* propertyName */ undefined, param.name)); + const paramName = createObjectBindingPattern(bindingElements); + + return createParameter( + /* decorators */ undefined, + /* modifiers */ undefined, + /* dotDotDotToken */ undefined, + paramName, + /* questionToken */ undefined, + paramType); + } + + interface ValidFunctionDeclaration extends MethodDeclaration { + name: PropertyName; body?: FunctionBody; typeParameters?: NodeArray; parameters: NodeArray; @@ -90,5 +110,9 @@ namespace ts.refactor.convertToNamedParameters { interface ValidParameterDeclaration extends ParameterDeclaration { name: Identifier; + type: TypeNode; + dotDotDotToken: undefined; + modifiers: undefined; + initializer: undefined; } } \ No newline at end of file From 23fc65a60c6d7b5e04c162812555bfa5cace8739 Mon Sep 17 00:00:00 2001 From: Gabriela Britto Date: Wed, 16 Jan 2019 16:32:32 -0800 Subject: [PATCH 005/149] implement new parameter creation --- .../refactors/convertToNamedParameters.ts | 30 ++++++------------- 1 file changed, 9 insertions(+), 21 deletions(-) diff --git a/src/services/refactors/convertToNamedParameters.ts b/src/services/refactors/convertToNamedParameters.ts index 0b5d3d265ff..aa3bf14a137 100644 --- a/src/services/refactors/convertToNamedParameters.ts +++ b/src/services/refactors/convertToNamedParameters.ts @@ -5,7 +5,6 @@ namespace ts.refactor.convertToNamedParameters { const actionNameNamedParameters = "Convert to named parameters"; const actionDescriptionNamedParameters = "Convert to named parameters"; const minimumParameterLength = 3; - const paramTypeNamePostfix = "Param"; registerRefactor(refactorName, { getEditsForAction, getAvailableActions }); @@ -30,15 +29,15 @@ namespace ts.refactor.convertToNamedParameters { const func = getFunctionDeclarationAtPosition(file, startPosition); if (!func) return undefined; - const paramTypeDeclaration = createParamTypeDeclaration(func); - const edits = textChanges.ChangeTracker.with(context, t => t.replaceNode(file, func, paramTypeDeclaration)); - // return undefined; + const newParamDeclaration = createObjectParameter(func); + const edits = textChanges.ChangeTracker.with(context, t => t.replaceNodeRangeWithNodes(file, first(func.parameters), last(func.parameters), createNodeArray([newParamDeclaration]))); return { renameFilename: undefined, renameLocation: undefined, edits }; } function getFunctionDeclarationAtPosition(file: SourceFile, startPosition: number): ValidFunctionDeclaration | undefined { const node = getTokenAtPosition(file, startPosition); const func = getContainingFunction(node); + // TODO: check range if (!func || !isValidFunctionDeclaration(func)) return undefined; return func; } @@ -62,21 +61,9 @@ namespace ts.refactor.convertToNamedParameters { return !paramDecl.modifiers && !paramDecl.dotDotDotToken && isIdentifier(paramDecl.name) && !paramDecl.initializer; } - function createParamTypeDeclaration(func: ValidFunctionDeclaration): InterfaceDeclaration { - const paramTypeName = getFunctionName(func); - const paramTypeMembers = ts.map(func.parameters, createPropertySignatureFromParameterDeclaration); - - return createInterfaceDeclaration( - /* decorators */ undefined, - /* modifiers */ undefined, - createIdentifier(paramTypeName), - func.typeParameters, - /* heritageClauses */ undefined, - createNodeArray(paramTypeMembers)); - } - - function getFunctionName(func: ValidFunctionDeclaration): string { - return declarationNameToString(func.name) + paramTypeNamePostfix; + function createParamTypeNode(func: ValidFunctionDeclaration): TypeLiteralNode { + const members = ts.map(func.parameters, createPropertySignatureFromParameterDeclaration); + return createTypeLiteralNode(members); } function createPropertySignatureFromParameterDeclaration(paramDeclaration: ValidParameterDeclaration): PropertySignature { @@ -88,9 +75,10 @@ namespace ts.refactor.convertToNamedParameters { paramDeclaration.initializer); } - function createParameterObjectBindingPattern(parameters: NodeArray, paramType: TypeNode): ParameterDeclaration { - const bindingElements = ts.map(parameters, param => createBindingElement(/* dotDotDotToken */ undefined, /* propertyName */ undefined, param.name)); + function createObjectParameter(func: ValidFunctionDeclaration): ParameterDeclaration { + const bindingElements = ts.map(func.parameters, param => createBindingElement(/* dotDotDotToken */ undefined, /* propertyName */ undefined, param.name)); const paramName = createObjectBindingPattern(bindingElements); + const paramType = createParamTypeNode(func); return createParameter( /* decorators */ undefined, From 919ed79f3a2795de226ce71873821b8da7ede7e2 Mon Sep 17 00:00:00 2001 From: Gabriela Britto Date: Wed, 16 Jan 2019 16:32:32 -0800 Subject: [PATCH 006/149] implement new parameter creation --- .../refactors/convertToNamedParameters.ts | 50 ++++++++----------- 1 file changed, 21 insertions(+), 29 deletions(-) diff --git a/src/services/refactors/convertToNamedParameters.ts b/src/services/refactors/convertToNamedParameters.ts index 0b5d3d265ff..fa46f56b169 100644 --- a/src/services/refactors/convertToNamedParameters.ts +++ b/src/services/refactors/convertToNamedParameters.ts @@ -4,8 +4,7 @@ namespace ts.refactor.convertToNamedParameters { const refactorDescription = "Convert to named parameters"; const actionNameNamedParameters = "Convert to named parameters"; const actionDescriptionNamedParameters = "Convert to named parameters"; - const minimumParameterLength = 3; - const paramTypeNamePostfix = "Param"; + const minimumParameterLength = 1; registerRefactor(refactorName, { getEditsForAction, getAvailableActions }); @@ -26,19 +25,21 @@ namespace ts.refactor.convertToNamedParameters { function getEditsForAction(context: RefactorContext, actionName: string): RefactorEditInfo | undefined { Debug.assert(actionName === actionNameNamedParameters); - const { file, startPosition } = context; + const { file, startPosition, program, cancellationToken } = context; const func = getFunctionDeclarationAtPosition(file, startPosition); - if (!func) return undefined; + if (!func || !cancellationToken) return undefined; - const paramTypeDeclaration = createParamTypeDeclaration(func); - const edits = textChanges.ChangeTracker.with(context, t => t.replaceNode(file, func, paramTypeDeclaration)); - // return undefined; + const newParamDeclaration = createObjectParameter(func); + // const funcRefs = FindAllReferences.getReferenceEntriesForNode(-1, func.name, program, program.getSourceFiles(), cancellationToken); + + const edits = textChanges.ChangeTracker.with(context, t => t.replaceNodeRange(file, first(func.parameters), last(func.parameters), newParamDeclaration)); return { renameFilename: undefined, renameLocation: undefined, edits }; } function getFunctionDeclarationAtPosition(file: SourceFile, startPosition: number): ValidFunctionDeclaration | undefined { const node = getTokenAtPosition(file, startPosition); const func = getContainingFunction(node); + // TODO: check range if (!func || !isValidFunctionDeclaration(func)) return undefined; return func; } @@ -55,28 +56,18 @@ namespace ts.refactor.convertToNamedParameters { } function isValidParameterNodeArray(parameters: NodeArray): boolean { - return parameters && parameters.length > minimumParameterLength && ts.every(parameters, isValidParameterDeclaration); + return parameters && parameters.length > minimumParameterLength && every(parameters, isValidParameterDeclaration); } function isValidParameterDeclaration(paramDecl: ParameterDeclaration): paramDecl is ValidParameterDeclaration { return !paramDecl.modifiers && !paramDecl.dotDotDotToken && isIdentifier(paramDecl.name) && !paramDecl.initializer; } - function createParamTypeDeclaration(func: ValidFunctionDeclaration): InterfaceDeclaration { - const paramTypeName = getFunctionName(func); - const paramTypeMembers = ts.map(func.parameters, createPropertySignatureFromParameterDeclaration); - - return createInterfaceDeclaration( - /* decorators */ undefined, - /* modifiers */ undefined, - createIdentifier(paramTypeName), - func.typeParameters, - /* heritageClauses */ undefined, - createNodeArray(paramTypeMembers)); - } - - function getFunctionName(func: ValidFunctionDeclaration): string { - return declarationNameToString(func.name) + paramTypeNamePostfix; + function createParamTypeNode(func: ValidFunctionDeclaration): TypeLiteralNode { + const members = map(func.parameters, createPropertySignatureFromParameterDeclaration); + const typeNode = addEmitFlags(createTypeLiteralNode(members), EmitFlags.SingleLine); + // TODO: add emit flags on create function in factory + return typeNode; } function createPropertySignatureFromParameterDeclaration(paramDeclaration: ValidParameterDeclaration): PropertySignature { @@ -88,16 +79,17 @@ namespace ts.refactor.convertToNamedParameters { paramDeclaration.initializer); } - function createParameterObjectBindingPattern(parameters: NodeArray, paramType: TypeNode): ParameterDeclaration { - const bindingElements = ts.map(parameters, param => createBindingElement(/* dotDotDotToken */ undefined, /* propertyName */ undefined, param.name)); + function createObjectParameter(func: ValidFunctionDeclaration): ParameterDeclaration { + const bindingElements = map(func.parameters, param => createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, getTextOfIdentifierOrLiteral(param.name))); const paramName = createObjectBindingPattern(bindingElements); + const paramType = createParamTypeNode(func); return createParameter( - /* decorators */ undefined, - /* modifiers */ undefined, - /* dotDotDotToken */ undefined, + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, paramName, - /* questionToken */ undefined, + /*questionToken*/ undefined, paramType); } From f3e60be8b12125c6ebf71c6eaa446223660b13dd Mon Sep 17 00:00:00 2001 From: Gabriela Britto Date: Mon, 28 Jan 2019 15:51:24 -0800 Subject: [PATCH 007/149] Move function getTypeNodeIfAccessible from inferFromUsage to utilities --- src/services/codefixes/inferFromUsage.ts | 24 ------------------------ src/services/utilities.ts | 24 ++++++++++++++++++++++++ 2 files changed, 24 insertions(+), 24 deletions(-) diff --git a/src/services/codefixes/inferFromUsage.ts b/src/services/codefixes/inferFromUsage.ts index 8e5b962116d..cb4e06e9dc5 100644 --- a/src/services/codefixes/inferFromUsage.ts +++ b/src/services/codefixes/inferFromUsage.ts @@ -294,30 +294,6 @@ namespace ts.codefix { } } - function getTypeNodeIfAccessible(type: Type, enclosingScope: Node, program: Program, host: LanguageServiceHost): TypeNode | undefined { - const checker = program.getTypeChecker(); - let typeIsAccessible = true; - const notAccessible = () => { typeIsAccessible = false; }; - const res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, { - trackSymbol: (symbol, declaration, meaning) => { - // TODO: GH#18217 - typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning!, /*shouldComputeAliasToMarkVisible*/ false).accessibility === SymbolAccessibility.Accessible; - }, - reportInaccessibleThisError: notAccessible, - reportPrivateInBaseOfClassExpression: notAccessible, - reportInaccessibleUniqueSymbolError: notAccessible, - moduleResolverHost: { - readFile: host.readFile, - fileExists: host.fileExists, - directoryExists: host.directoryExists, - getSourceFiles: program.getSourceFiles, - getCurrentDirectory: program.getCurrentDirectory, - getCommonSourceDirectory: program.getCommonSourceDirectory, - } - }); - return typeIsAccessible ? res : undefined; - } - function getReferences(token: PropertyName | Token, program: Program, cancellationToken: CancellationToken): ReadonlyArray { // Position shouldn't matter since token is not a SourceFile. return mapDefined(FindAllReferences.getReferenceEntriesForNode(-1, token, program, program.getSourceFiles(), cancellationToken), entry => diff --git a/src/services/utilities.ts b/src/services/utilities.ts index 2f78ef2324b..0574afe34bd 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -1911,4 +1911,28 @@ namespace ts { export function getSwitchedType(caseClause: CaseClause, checker: TypeChecker): Type | undefined { return checker.getTypeAtLocation(caseClause.parent.parent.expression); } + + export function getTypeNodeIfAccessible(type: Type, enclosingScope: Node, program: Program, host: LanguageServiceHost): TypeNode | undefined { + const checker = program.getTypeChecker(); + let typeIsAccessible = true; + const notAccessible = () => { typeIsAccessible = false; }; + const res = checker.typeToTypeNode(type, enclosingScope, /*flags*/ undefined, { + trackSymbol: (symbol, declaration, meaning) => { + // TODO: GH#18217 + typeIsAccessible = typeIsAccessible && checker.isSymbolAccessible(symbol, declaration, meaning!, /*shouldComputeAliasToMarkVisible*/ false).accessibility === SymbolAccessibility.Accessible; + }, + reportInaccessibleThisError: notAccessible, + reportPrivateInBaseOfClassExpression: notAccessible, + reportInaccessibleUniqueSymbolError: notAccessible, + moduleResolverHost: { + readFile: host.readFile, + fileExists: host.fileExists, + directoryExists: host.directoryExists, + getSourceFiles: program.getSourceFiles, + getCurrentDirectory: program.getCurrentDirectory, + getCommonSourceDirectory: program.getCommonSourceDirectory, + } + }); + return typeIsAccessible ? res : undefined; + } } From 3243b4b4f2c6d066abfd1472e8eeae527edcdd18 Mon Sep 17 00:00:00 2001 From: Gabriela Britto Date: Mon, 28 Jan 2019 15:52:44 -0800 Subject: [PATCH 008/149] Refactor direct function calls --- .../refactors/convertToNamedParameters.ts | 211 ++++++++++++++---- 1 file changed, 171 insertions(+), 40 deletions(-) diff --git a/src/services/refactors/convertToNamedParameters.ts b/src/services/refactors/convertToNamedParameters.ts index fa46f56b169..a6d75662e47 100644 --- a/src/services/refactors/convertToNamedParameters.ts +++ b/src/services/refactors/convertToNamedParameters.ts @@ -10,7 +10,7 @@ namespace ts.refactor.convertToNamedParameters { function getAvailableActions(context: RefactorContext): ReadonlyArray { const { file, startPosition } = context; - const func = getFunctionDeclarationAtPosition(file, startPosition); + const func = getFunctionDeclarationAtPosition(file, startPosition, context.program.getTypeChecker()); if (!func) return emptyArray; return [{ @@ -25,32 +25,102 @@ namespace ts.refactor.convertToNamedParameters { function getEditsForAction(context: RefactorContext, actionName: string): RefactorEditInfo | undefined { Debug.assert(actionName === actionNameNamedParameters); - const { file, startPosition, program, cancellationToken } = context; - const func = getFunctionDeclarationAtPosition(file, startPosition); + const { file, startPosition, program, cancellationToken, host } = context; + const func = getFunctionDeclarationAtPosition(file, startPosition, program.getTypeChecker()); if (!func || !cancellationToken) return undefined; - const newParamDeclaration = createObjectParameter(func); - // const funcRefs = FindAllReferences.getReferenceEntriesForNode(-1, func.name, program, program.getSourceFiles(), cancellationToken); - - const edits = textChanges.ChangeTracker.with(context, t => t.replaceNodeRange(file, first(func.parameters), last(func.parameters), newParamDeclaration)); + const edits = textChanges.ChangeTracker.with(context, t => doChange(file, program, cancellationToken, host, t, func)); return { renameFilename: undefined, renameLocation: undefined, edits }; } - function getFunctionDeclarationAtPosition(file: SourceFile, startPosition: number): ValidFunctionDeclaration | undefined { + function doChange(sourceFile: SourceFile, program: Program, cancellationToken: CancellationToken, host: LanguageServiceHost, changes: textChanges.ChangeTracker, functionDeclaration: ValidFunctionDeclaration): void { + const newParamDeclaration = getSynthesizedDeepClone(createObjectParameter(functionDeclaration, program, host)); + changes.replaceNodeRange(sourceFile, first(functionDeclaration.parameters), last(functionDeclaration.parameters), newParamDeclaration); + + const nameNode = getFunctionDeclarationName(functionDeclaration); + const functionRefs = FindAllReferences.getReferenceEntriesForNode(-1, nameNode, program, program.getSourceFiles(), cancellationToken); + const functionCalls = getDirectFunctionCalls(functionRefs); + + forEach(functionCalls, call => { + if (call.arguments && call.arguments.length) { + const newArguments = getSynthesizedDeepClone(createArgumentObject(functionDeclaration, call)); + changes.replaceNodeRange(getSourceFileOfNode(call), first(call.arguments), last(call.arguments), newArguments); + }}); + } + + function createArgumentObject(func: ValidFunctionDeclaration, funcCall: CallExpression | NewExpression): ObjectLiteralExpression { + const properties = map(funcCall.arguments, (arg, i) => createPropertyAssignment(getParameterName(func.parameters[i]), arg)); + return createObjectLiteral(properties, /*multiLine*/ false); + } + + function getDirectFunctionCalls(referenceEntries: ReadonlyArray | undefined): ReadonlyArray { + return mapDefined(referenceEntries, (entry) => { + if (entry.kind !== FindAllReferences.EntryKind.Span && entry.node.parent) { + const functionRef = entry.node; + const parent = functionRef.parent; + switch (parent.kind) { + // Function call (foo(...)) + case SyntaxKind.CallExpression: + const callExpression = tryCast(parent, isCallExpression); + if (callExpression && callExpression.expression === functionRef) { + return callExpression; + } + break; + // Constructor call (new Foo(...)) + case SyntaxKind.NewExpression: + const newExpression = tryCast(parent, isNewExpression); + if (newExpression && newExpression.expression === functionRef) { + return newExpression; + } + break; + // Method call (x.foo(...)) + case SyntaxKind.PropertyAccessExpression: + const propertyAccessExpression = tryCast(parent, isPropertyAccessExpression); + if (propertyAccessExpression && propertyAccessExpression.parent && propertyAccessExpression.name === functionRef) { + const callExpression = tryCast(propertyAccessExpression.parent, isCallExpression); + if (callExpression && callExpression.expression === propertyAccessExpression) { + return callExpression; + } + } + break; + // Method call (x['foo'](...)) + case SyntaxKind.ElementAccessExpression: + const elementAccessExpression = tryCast(parent, isElementAccessExpression); + if (elementAccessExpression && elementAccessExpression.parent && elementAccessExpression.argumentExpression === functionRef) { + const callExpression = tryCast(elementAccessExpression.parent, isCallExpression); + if (callExpression && callExpression.expression === elementAccessExpression) { + return callExpression; + } + } + break; + } + } + return undefined; + }); + } + + function getFunctionDeclarationAtPosition(file: SourceFile, startPosition: number, checker: TypeChecker): ValidFunctionDeclaration | undefined { const node = getTokenAtPosition(file, startPosition); const func = getContainingFunction(node); - // TODO: check range - if (!func || !isValidFunctionDeclaration(func)) return undefined; + if (!func || !isValidFunctionDeclaration(func, checker) || !rangeContainsRange(func, node) || (func.body && rangeContainsRange(func.body, node))) return undefined; return func; } - function isValidFunctionDeclaration(func: SignatureDeclaration): func is ValidFunctionDeclaration { + function isValidFunctionDeclaration(func: SignatureDeclaration, checker: TypeChecker): func is ValidFunctionDeclaration { switch (func.kind) { case SyntaxKind.FunctionDeclaration: case SyntaxKind.MethodDeclaration: + return !!func.name && isPropertyName(func.name) && isValidParameterNodeArray(func.parameters) && !!func.body && !checker.isImplementationOfOverload(func); case SyntaxKind.Constructor: - return !!(func.name && isValidParameterNodeArray(func.parameters)); - default: + if (isClassDeclaration(func.parent)) { + return !!func.parent.name && isValidParameterNodeArray(func.parameters) && !!func.body && !checker.isImplementationOfOverload(func); + } + else { + return isVariableDeclaration(func.parent.parent) && isVarConst(func.parent.parent) && isValidParameterNodeArray(func.parameters) && !!func.body && !checker.isImplementationOfOverload(func); + } + case SyntaxKind.FunctionExpression: + case SyntaxKind.ArrowFunction: + return isVariableDeclaration(func.parent) && isVarConst(func.parent) && isValidParameterNodeArray(func.parameters); } return false; } @@ -60,29 +130,25 @@ namespace ts.refactor.convertToNamedParameters { } function isValidParameterDeclaration(paramDecl: ParameterDeclaration): paramDecl is ValidParameterDeclaration { - return !paramDecl.modifiers && !paramDecl.dotDotDotToken && isIdentifier(paramDecl.name) && !paramDecl.initializer; + return !paramDecl.modifiers && !paramDecl.dotDotDotToken && isIdentifier(paramDecl.name); } - function createParamTypeNode(func: ValidFunctionDeclaration): TypeLiteralNode { - const members = map(func.parameters, createPropertySignatureFromParameterDeclaration); - const typeNode = addEmitFlags(createTypeLiteralNode(members), EmitFlags.SingleLine); - // TODO: add emit flags on create function in factory - return typeNode; - } - - function createPropertySignatureFromParameterDeclaration(paramDeclaration: ValidParameterDeclaration): PropertySignature { - return createPropertySignature( - /*modifiers*/ undefined, - paramDeclaration.name, - paramDeclaration.questionToken, - paramDeclaration.type, - paramDeclaration.initializer); - } - - function createObjectParameter(func: ValidFunctionDeclaration): ParameterDeclaration { - const bindingElements = map(func.parameters, param => createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, getTextOfIdentifierOrLiteral(param.name))); + function createObjectParameter(functionDeclaration: ValidFunctionDeclaration, program: Program, host: LanguageServiceHost): ParameterDeclaration { + const bindingElements = map( + functionDeclaration.parameters, + paramDecl => { + return createBindingElement( + /*dotDotDotToken*/ undefined, + /*propertyName*/ undefined, + getParameterName(paramDecl), + paramDecl.initializer); }); const paramName = createObjectBindingPattern(bindingElements); - const paramType = createParamTypeNode(func); + const paramType = createParamTypeNode(functionDeclaration); + + let objectInitializer: Expression | undefined; + if (every(functionDeclaration.parameters, param => !!param.initializer || !!param.questionToken)) { + objectInitializer = createObjectLiteral(); + } return createParameter( /*decorators*/ undefined, @@ -90,21 +156,86 @@ namespace ts.refactor.convertToNamedParameters { /*dotDotDotToken*/ undefined, paramName, /*questionToken*/ undefined, - paramType); + paramType, + objectInitializer); + + function createParamTypeNode(func: ValidFunctionDeclaration): TypeLiteralNode { + const members = map(func.parameters, createPropertySignatureFromParameterDeclaration); + const typeNode = addEmitFlags(createTypeLiteralNode(members), EmitFlags.SingleLine); + return typeNode; + } + + function createPropertySignatureFromParameterDeclaration(paramDeclaration: ValidParameterDeclaration): PropertySignature { + let paramType = paramDeclaration.type; + if (paramDeclaration.initializer && !paramType) { + const checker = program.getTypeChecker(); + const type = checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(paramDeclaration.initializer)); + paramType = getTypeNodeIfAccessible(type, paramDeclaration, program, host); + } + return createPropertySignature( + /*modifiers*/ undefined, + paramDeclaration.name, + paramDeclaration.initializer ? createToken(SyntaxKind.QuestionToken) : paramDeclaration.questionToken, + paramType, + /*initializer*/ undefined); + } } - interface ValidFunctionDeclaration extends MethodDeclaration { - name: PropertyName; - body?: FunctionBody; - typeParameters?: NodeArray; + function getParameterName(paramDecl: ValidParameterDeclaration): string { + return getTextOfIdentifierOrLiteral(paramDecl.name); + } + + function getFunctionDeclarationName(functionDeclaration: ValidFunctionDeclaration): Node { + switch (functionDeclaration.kind) { + case SyntaxKind.FunctionDeclaration: + case SyntaxKind.MethodDeclaration: + return functionDeclaration.name; + case SyntaxKind.Constructor: + switch (functionDeclaration.parent.kind) { + case SyntaxKind.ClassDeclaration: + return functionDeclaration.parent.name; + case SyntaxKind.ClassExpression: + return functionDeclaration.parent.parent.name; + default: return Debug.assertNever(functionDeclaration.parent); + } + case SyntaxKind.ArrowFunction: + case SyntaxKind.FunctionExpression: + return functionDeclaration.parent.name; + } + } + + interface ValidConstructor extends ConstructorDeclaration { + parent: (ClassDeclaration & { name: Identifier }) | (ClassExpression & { parent: VariableDeclaration }); + parameters: NodeArray; + body: FunctionBody; + } + + interface ValidFunction extends FunctionDeclaration { + name: Identifier; + parameters: NodeArray; + body: FunctionBody; + } + + interface ValidMethod extends MethodDeclaration { + parameters: NodeArray; + body: FunctionBody; + } + + interface ValidFunctionExpression extends FunctionExpression { + parent: VariableDeclaration; parameters: NodeArray; } + interface ValidArrowFunction extends ArrowFunction { + parent: VariableDeclaration; + parameters: NodeArray; + } + + type ValidFunctionDeclaration = ValidConstructor | ValidFunction | ValidMethod | ValidArrowFunction | ValidFunctionExpression; + interface ValidParameterDeclaration extends ParameterDeclaration { name: Identifier; - type: TypeNode; dotDotDotToken: undefined; modifiers: undefined; - initializer: undefined; } } \ No newline at end of file From b668e342c449d70002bfcfb5ed6d3eb26c684cbd Mon Sep 17 00:00:00 2001 From: Gabriela Britto Date: Mon, 28 Jan 2019 15:53:39 -0800 Subject: [PATCH 009/149] Add tests for convert to named parameters refactor --- .../refactorConvertToNamedParameters.ts | 4 ++- .../refactorConvertToNamedParameters1.ts | 23 ++++++++++++++++ .../refactorConvertToNamedParameters10.ts | 7 +++++ .../refactorConvertToNamedParameters11.ts | 13 +++++++++ .../refactorConvertToNamedParameters12.ts | 13 +++++++++ .../refactorConvertToNamedParameters13.ts | 7 +++++ .../refactorConvertToNamedParameters14.ts | 17 ++++++++++++ .../refactorConvertToNamedParameters15.ts | 8 ++++++ .../refactorConvertToNamedParameters16.ts | 23 ++++++++++++++++ .../refactorConvertToNamedParameters17.ts | 17 ++++++++++++ .../refactorConvertToNamedParameters2.ts | 27 +++++++++++++++++++ .../refactorConvertToNamedParameters3.ts | 21 +++++++++++++++ .../refactorConvertToNamedParameters4.ts | 17 ++++++++++++ .../refactorConvertToNamedParameters5.ts | 23 ++++++++++++++++ .../refactorConvertToNamedParameters6.ts | 17 ++++++++++++ .../refactorConvertToNamedParameters7.ts | 17 ++++++++++++ .../refactorConvertToNamedParameters8.ts | 17 ++++++++++++ .../refactorConvertToNamedParameters9.ts | 10 +++++++ 18 files changed, 280 insertions(+), 1 deletion(-) create mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters1.ts create mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters10.ts create mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters11.ts create mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters12.ts create mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters13.ts create mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters14.ts create mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters15.ts create mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters16.ts create mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters17.ts create mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters2.ts create mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters3.ts create mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters4.ts create mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters5.ts create mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters6.ts create mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters7.ts create mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters8.ts create mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters9.ts diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters.ts b/tests/cases/fourslash/refactorConvertToNamedParameters.ts index e160dd471c0..0834bf288fc 100644 --- a/tests/cases/fourslash/refactorConvertToNamedParameters.ts +++ b/tests/cases/fourslash/refactorConvertToNamedParameters.ts @@ -3,6 +3,7 @@ ////function f(/*a*/a: number, b: string/*b*/): string { //// return b; ////} +////f(4, "b"); goTo.select("a", "b"); edit.applyRefactor({ @@ -11,5 +12,6 @@ edit.applyRefactor({ actionDescription: "Convert to named parameters", newContent: `function f({ a, b }: { a: number; b: string; }): string { return b; -}` +} +f({ a: 4, b: "b" });` }); \ No newline at end of file diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters1.ts b/tests/cases/fourslash/refactorConvertToNamedParameters1.ts new file mode 100644 index 00000000000..d7dce948cae --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToNamedParameters1.ts @@ -0,0 +1,23 @@ +/// + +////class Foo { +//// /*a*/bar/*b*/(t: string, s: string): string { +//// return s + t; +//// } +////} +////var foo = new Foo(); +////foo.bar("a", "b"); + +goTo.select("a", "b"); +edit.applyRefactor({ + refactorName: "Convert to named parameters", + actionName: "Convert to named parameters", + actionDescription: "Convert to named parameters", + newContent: `class Foo { + bar({ t, s }: { t: string; s: string; }): string { + return s + t; + } +} +var foo = new Foo(); +foo.bar({ t: "a", s: "b" });` +}); \ No newline at end of file diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters10.ts b/tests/cases/fourslash/refactorConvertToNamedParameters10.ts new file mode 100644 index 00000000000..209a06d5bfa --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToNamedParameters10.ts @@ -0,0 +1,7 @@ +/// + +////const { foo, bar } = { foo: /*a*/(a: number, b: number)/*b*/ => {}, bar: () => {} }; +////foo(1, 2); + +goTo.select("a", "b"); +verify.not.refactorAvailable("Convert to named parameters"); diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters11.ts b/tests/cases/fourslash/refactorConvertToNamedParameters11.ts new file mode 100644 index 00000000000..cbacbf1f21a --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToNamedParameters11.ts @@ -0,0 +1,13 @@ +/// + +////const foo = /*a*/function/*b*/(a: number, b: number) {}; +////foo(1, 2); + +goTo.select("a", "b"); +edit.applyRefactor({ + refactorName: "Convert to named parameters", + actionName: "Convert to named parameters", + actionDescription: "Convert to named parameters", + newContent: `const foo = function({ a, b }: { a: number; b: number; }) {}; +foo({ a: 1, b: 2 });` +}); \ No newline at end of file diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters12.ts b/tests/cases/fourslash/refactorConvertToNamedParameters12.ts new file mode 100644 index 00000000000..6a2fbdc6f04 --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToNamedParameters12.ts @@ -0,0 +1,13 @@ +/// + +////const foo = /*a*/(a: number, b: number)/*b*/ => {}; +////foo(1, 2); + +goTo.select("a", "b"); +edit.applyRefactor({ + refactorName: "Convert to named parameters", + actionName: "Convert to named parameters", + actionDescription: "Convert to named parameters", + newContent: `const foo = ({ a, b }: { a: number; b: number; }) => {}; +foo({ a: 1, b: 2 });` +}); \ No newline at end of file diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters13.ts b/tests/cases/fourslash/refactorConvertToNamedParameters13.ts new file mode 100644 index 00000000000..ec25b50b067 --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToNamedParameters13.ts @@ -0,0 +1,7 @@ +/// + +////var foo = /*a*/(a: number, b: number)/*b*/ => {}; +////foo(1, 2); + +goTo.select("a", "b"); +verify.not.refactorAvailable("Convert to named parameters"); diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters14.ts b/tests/cases/fourslash/refactorConvertToNamedParameters14.ts new file mode 100644 index 00000000000..a7914bc9f1f --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToNamedParameters14.ts @@ -0,0 +1,17 @@ +/// + +////const c = class { +//// constructor(/*a*/a: number, b = { x: 1 }/*b*/) {} +////} +////var x = new c(2); + +goTo.select("a", "b"); +edit.applyRefactor({ + refactorName: "Convert to named parameters", + actionName: "Convert to named parameters", + actionDescription: "Convert to named parameters", + newContent: `const c = class { + constructor({ a, b = { x: 1 } }: { a: number; b?: { x: number; }; }) {} +} +var x = new c({ a: 2 });` +}); diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters15.ts b/tests/cases/fourslash/refactorConvertToNamedParameters15.ts new file mode 100644 index 00000000000..a056a82871b --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToNamedParameters15.ts @@ -0,0 +1,8 @@ +/// + +/////export default class { +//// constructor(/*a*/a: number, b = { x: 1 }/*b*/) {} +////} + +goTo.select("a", "b"); +verify.not.refactorAvailable("Convert to named parameters"); diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters16.ts b/tests/cases/fourslash/refactorConvertToNamedParameters16.ts new file mode 100644 index 00000000000..7d626215572 --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToNamedParameters16.ts @@ -0,0 +1,23 @@ +/// + +////class Foo { +//// /*a*/bar/*b*/(t: T, s: T) { +//// return s; +//// } +////} +////var foo = new Foo(); +////foo.bar("a", "b"); + +goTo.select("a", "b"); +edit.applyRefactor({ + refactorName: "Convert to named parameters", + actionName: "Convert to named parameters", + actionDescription: "Convert to named parameters", + newContent: `class Foo { + bar({ t, s }: { t: T; s: T; }) { + return s; + } +} +var foo = new Foo(); +foo.bar({ t: "a", s: "b" });` +}); \ No newline at end of file diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters17.ts b/tests/cases/fourslash/refactorConvertToNamedParameters17.ts new file mode 100644 index 00000000000..5af97ca694a --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToNamedParameters17.ts @@ -0,0 +1,17 @@ +/// + +////function foo(/*a*/t: T, s: S/*b*/) { +//// return s; +////} +////foo("a", "b"); + +goTo.select("a", "b"); +edit.applyRefactor({ + refactorName: "Convert to named parameters", + actionName: "Convert to named parameters", + actionDescription: "Convert to named parameters", + newContent: `function foo({ t, s }: { t: T; s: S; }) { + return s; +} +foo({ t: "a", s: "b" });` +}); \ No newline at end of file diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters2.ts b/tests/cases/fourslash/refactorConvertToNamedParameters2.ts new file mode 100644 index 00000000000..86b1f9eb610 --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToNamedParameters2.ts @@ -0,0 +1,27 @@ +/// + +////class Foo { +//// t: string; +//// s: string; +//// /*a*/constructor/*b*/(t: string, s: string) { +//// this.t = t; +//// this.s = s; +//// } +////} +////var foo = new Foo("a", "b"); + +goTo.select("a", "b"); +edit.applyRefactor({ + refactorName: "Convert to named parameters", + actionName: "Convert to named parameters", + actionDescription: "Convert to named parameters", + newContent: `class Foo { + t: string; + s: string; + constructor({ t, s }: { t: string; s: string; }) { + this.t = t; + this.s = s; + } +} +var foo = new Foo({ t: "a", s: "b" });` +}); \ No newline at end of file diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters3.ts b/tests/cases/fourslash/refactorConvertToNamedParameters3.ts new file mode 100644 index 00000000000..c84c1aa20d4 --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToNamedParameters3.ts @@ -0,0 +1,21 @@ +/// + +////class Foo { +//// static /*a*/bar/*b*/(t: string, s: string): string { +//// return s + t; +//// } +////} +////Foo.bar("a", "b"); + +goTo.select("a", "b"); +edit.applyRefactor({ + refactorName: "Convert to named parameters", + actionName: "Convert to named parameters", + actionDescription: "Convert to named parameters", + newContent: `class Foo { + static bar({ t, s }: { t: string; s: string; }): string { + return s + t; + } +} +Foo.bar({ t: "a", s: "b" });` +}); \ No newline at end of file diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters4.ts b/tests/cases/fourslash/refactorConvertToNamedParameters4.ts new file mode 100644 index 00000000000..b6bdb7a88c2 --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToNamedParameters4.ts @@ -0,0 +1,17 @@ +/// + +////function f(/*a*/a: number, b = { x: 1, z: { s: true } }/*b*/) { +//// return b; +////} +////f(2); + +goTo.select("a", "b"); +edit.applyRefactor({ + refactorName: "Convert to named parameters", + actionName: "Convert to named parameters", + actionDescription: "Convert to named parameters", + newContent: `function f({ a, b = { x: 1, z: { s: true } } }: { a: number; b?: { x: number; z: { s: boolean; }; }; }) { + return b; +} +f({ a: 2 });` +}); \ No newline at end of file diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters5.ts b/tests/cases/fourslash/refactorConvertToNamedParameters5.ts new file mode 100644 index 00000000000..8b8958bc674 --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToNamedParameters5.ts @@ -0,0 +1,23 @@ +/// + +////class Foo { +//// /*a*/bar/*b*/(t: string, s: string): string { +//// return s + t; +//// } +////} +////var foo = new Foo(); +////foo['bar']("a", "b"); + +goTo.select("a", "b"); +edit.applyRefactor({ + refactorName: "Convert to named parameters", + actionName: "Convert to named parameters", + actionDescription: "Convert to named parameters", + newContent: `class Foo { + bar({ t, s }: { t: string; s: string; }): string { + return s + t; + } +} +var foo = new Foo(); +foo['bar']({ t: "a", s: "b" });` +}); \ No newline at end of file diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters6.ts b/tests/cases/fourslash/refactorConvertToNamedParameters6.ts new file mode 100644 index 00000000000..1e63f44fc35 --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToNamedParameters6.ts @@ -0,0 +1,17 @@ +/// + +////function f(/*a*/a: number, b: string = "1"/*b*/): string { +//// return b; +////} +////f(4, "b"); + +goTo.select("a", "b"); +edit.applyRefactor({ + refactorName: "Convert to named parameters", + actionName: "Convert to named parameters", + actionDescription: "Convert to named parameters", + newContent: `function f({ a, b = "1" }: { a: number; b?: string; }): string { + return b; +} +f({ a: 4, b: "b" });` +}); \ No newline at end of file diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters7.ts b/tests/cases/fourslash/refactorConvertToNamedParameters7.ts new file mode 100644 index 00000000000..825b34c303d --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToNamedParameters7.ts @@ -0,0 +1,17 @@ +/// + +////function f(/*a*/a?: number, b: string = "1"/*b*/): string { +//// return b; +////} +////f(); + +goTo.select("a", "b"); +edit.applyRefactor({ + refactorName: "Convert to named parameters", + actionName: "Convert to named parameters", + actionDescription: "Convert to named parameters", + newContent: `function f({ a, b = "1" }: { a?: number; b?: string; } = {}): string { + return b; +} +f();` +}); \ No newline at end of file diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters8.ts b/tests/cases/fourslash/refactorConvertToNamedParameters8.ts new file mode 100644 index 00000000000..2c3d7de339f --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToNamedParameters8.ts @@ -0,0 +1,17 @@ +/// + +////function f(/*a*/a: number, b = 1/*b*/) { +//// return b; +////} +////f(2); + +goTo.select("a", "b"); +edit.applyRefactor({ + refactorName: "Convert to named parameters", + actionName: "Convert to named parameters", + actionDescription: "Convert to named parameters", + newContent: `function f({ a, b = 1 }: { a: number; b?: number; }) { + return b; +} +f({ a: 2 });` +}); \ No newline at end of file diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters9.ts b/tests/cases/fourslash/refactorConvertToNamedParameters9.ts new file mode 100644 index 00000000000..772f8ea8848 --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToNamedParameters9.ts @@ -0,0 +1,10 @@ +/// + +////function f(a: number, b: number); +////function f(/*a*/a: number, b = 1/*b*/) { +//// return b; +////} +////f(2); + +goTo.select("a", "b"); +verify.not.refactorAvailable("Convert to named parameters"); \ No newline at end of file From 1d94322ea074b716a5ee51c099317816a497a1e5 Mon Sep 17 00:00:00 2001 From: Gabriela Britto Date: Tue, 29 Jan 2019 16:44:30 -0800 Subject: [PATCH 010/149] preserve this parameter when refactoring --- .../refactors/convertToNamedParameters.ts | 54 +++++++++++++++---- 1 file changed, 43 insertions(+), 11 deletions(-) diff --git a/src/services/refactors/convertToNamedParameters.ts b/src/services/refactors/convertToNamedParameters.ts index a6d75662e47..3e7e2ca91ed 100644 --- a/src/services/refactors/convertToNamedParameters.ts +++ b/src/services/refactors/convertToNamedParameters.ts @@ -34,8 +34,9 @@ namespace ts.refactor.convertToNamedParameters { } function doChange(sourceFile: SourceFile, program: Program, cancellationToken: CancellationToken, host: LanguageServiceHost, changes: textChanges.ChangeTracker, functionDeclaration: ValidFunctionDeclaration): void { - const newParamDeclaration = getSynthesizedDeepClone(createObjectParameter(functionDeclaration, program, host)); - changes.replaceNodeRange(sourceFile, first(functionDeclaration.parameters), last(functionDeclaration.parameters), newParamDeclaration); + const newParamDeclaration = map(createObjectParameter(functionDeclaration, program, host), node => getSynthesizedDeepClone(node, /*includeTrivia*/ false)); + const newFunctionDeclaration = updateDeclarationParameters(functionDeclaration, createNodeArray(newParamDeclaration)); + changes.replaceNode(sourceFile, functionDeclaration, newFunctionDeclaration); const nameNode = getFunctionDeclarationName(functionDeclaration); const functionRefs = FindAllReferences.getReferenceEntriesForNode(-1, nameNode, program, program.getSourceFiles(), cancellationToken); @@ -48,8 +49,15 @@ namespace ts.refactor.convertToNamedParameters { }}); } + function updateDeclarationParameters(declaration: SignatureDeclaration, parameters: NodeArray): SignatureDeclaration { + const newDeclaration = getSynthesizedClone(declaration); + newDeclaration.parameters = parameters; + return updateNode(newDeclaration, declaration); + } + function createArgumentObject(func: ValidFunctionDeclaration, funcCall: CallExpression | NewExpression): ObjectLiteralExpression { - const properties = map(funcCall.arguments, (arg, i) => createPropertyAssignment(getParameterName(func.parameters[i]), arg)); + const parameters = getRefactorableParameters(func.parameters); + const properties = map(funcCall.arguments, (arg, i) => createPropertyAssignment(getParameterName(parameters[i]), arg)); return createObjectLiteral(properties, /*multiLine*/ false); } @@ -126,16 +134,35 @@ namespace ts.refactor.convertToNamedParameters { } function isValidParameterNodeArray(parameters: NodeArray): boolean { - return parameters && parameters.length > minimumParameterLength && every(parameters, isValidParameterDeclaration); + return parameters && getRefactorableParametersLength(parameters) > minimumParameterLength && every(parameters, isValidParameterDeclaration); } function isValidParameterDeclaration(paramDecl: ParameterDeclaration): paramDecl is ValidParameterDeclaration { return !paramDecl.modifiers && !paramDecl.dotDotDotToken && isIdentifier(paramDecl.name); } - function createObjectParameter(functionDeclaration: ValidFunctionDeclaration, program: Program, host: LanguageServiceHost): ParameterDeclaration { + function hasThisParameter(parameters: NodeArray): boolean { + return isThis(parameters[0].name); + } + + function getRefactorableParametersLength(parameters: NodeArray): number { + if (hasThisParameter(parameters)) { + return parameters.length - 1; + } + return parameters.length; + } + + function getRefactorableParameters(parameters: NodeArray): NodeArray { + if (hasThisParameter(parameters)) { + parameters = createNodeArray(parameters.slice(1), parameters.hasTrailingComma); + } + return parameters; + } + + function createObjectParameter(functionDeclaration: ValidFunctionDeclaration, program: Program, host: LanguageServiceHost): NodeArray { + const refactorableParameters = getRefactorableParameters(functionDeclaration.parameters); const bindingElements = map( - functionDeclaration.parameters, + refactorableParameters, paramDecl => { return createBindingElement( /*dotDotDotToken*/ undefined, @@ -143,14 +170,14 @@ namespace ts.refactor.convertToNamedParameters { getParameterName(paramDecl), paramDecl.initializer); }); const paramName = createObjectBindingPattern(bindingElements); - const paramType = createParamTypeNode(functionDeclaration); + const paramType = createParamTypeNode(refactorableParameters); let objectInitializer: Expression | undefined; - if (every(functionDeclaration.parameters, param => !!param.initializer || !!param.questionToken)) { + if (every(refactorableParameters, param => !!param.initializer || !!param.questionToken)) { objectInitializer = createObjectLiteral(); } - return createParameter( + const newParameter = createParameter( /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, @@ -159,8 +186,13 @@ namespace ts.refactor.convertToNamedParameters { paramType, objectInitializer); - function createParamTypeNode(func: ValidFunctionDeclaration): TypeLiteralNode { - const members = map(func.parameters, createPropertySignatureFromParameterDeclaration); + if (hasThisParameter(functionDeclaration.parameters)) { + return createNodeArray([functionDeclaration.parameters[0], newParameter]); + } + return createNodeArray([newParameter]); + + function createParamTypeNode(parameters: NodeArray): TypeLiteralNode { + const members = map(parameters, createPropertySignatureFromParameterDeclaration); const typeNode = addEmitFlags(createTypeLiteralNode(members), EmitFlags.SingleLine); return typeNode; } From 050c70a4c08d322bdae49b3489d7e7a9e56d7fa8 Mon Sep 17 00:00:00 2001 From: Gabriela Britto Date: Tue, 29 Jan 2019 16:45:52 -0800 Subject: [PATCH 011/149] update tests formatting --- tests/cases/fourslash/refactorConvertToNamedParameters11.ts | 4 ++-- tests/cases/fourslash/refactorConvertToNamedParameters12.ts | 4 ++-- tests/cases/fourslash/refactorConvertToNamedParameters14.ts | 4 ++-- tests/cases/fourslash/refactorConvertToNamedParameters17.ts | 2 +- tests/cases/fourslash/refactorConvertToNamedParameters5.ts | 4 +++- 5 files changed, 10 insertions(+), 8 deletions(-) diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters11.ts b/tests/cases/fourslash/refactorConvertToNamedParameters11.ts index cbacbf1f21a..e8aa6a92dd8 100644 --- a/tests/cases/fourslash/refactorConvertToNamedParameters11.ts +++ b/tests/cases/fourslash/refactorConvertToNamedParameters11.ts @@ -1,6 +1,6 @@ /// -////const foo = /*a*/function/*b*/(a: number, b: number) {}; +////const foo = /*a*/function/*b*/(a: number, b: number) { }; ////foo(1, 2); goTo.select("a", "b"); @@ -8,6 +8,6 @@ edit.applyRefactor({ refactorName: "Convert to named parameters", actionName: "Convert to named parameters", actionDescription: "Convert to named parameters", - newContent: `const foo = function({ a, b }: { a: number; b: number; }) {}; + newContent: `const foo = function({ a, b }: { a: number; b: number; }) { }; foo({ a: 1, b: 2 });` }); \ No newline at end of file diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters12.ts b/tests/cases/fourslash/refactorConvertToNamedParameters12.ts index 6a2fbdc6f04..6a5a8e328a5 100644 --- a/tests/cases/fourslash/refactorConvertToNamedParameters12.ts +++ b/tests/cases/fourslash/refactorConvertToNamedParameters12.ts @@ -1,6 +1,6 @@ /// -////const foo = /*a*/(a: number, b: number)/*b*/ => {}; +////const foo = /*a*/(a: number, b: number)/*b*/ => { }; ////foo(1, 2); goTo.select("a", "b"); @@ -8,6 +8,6 @@ edit.applyRefactor({ refactorName: "Convert to named parameters", actionName: "Convert to named parameters", actionDescription: "Convert to named parameters", - newContent: `const foo = ({ a, b }: { a: number; b: number; }) => {}; + newContent: `const foo = ({ a, b }: { a: number; b: number; }) => { }; foo({ a: 1, b: 2 });` }); \ No newline at end of file diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters14.ts b/tests/cases/fourslash/refactorConvertToNamedParameters14.ts index a7914bc9f1f..ee4b6051756 100644 --- a/tests/cases/fourslash/refactorConvertToNamedParameters14.ts +++ b/tests/cases/fourslash/refactorConvertToNamedParameters14.ts @@ -1,7 +1,7 @@ /// ////const c = class { -//// constructor(/*a*/a: number, b = { x: 1 }/*b*/) {} +//// constructor(/*a*/a: number, b = { x: 1 }/*b*/) { } ////} ////var x = new c(2); @@ -11,7 +11,7 @@ edit.applyRefactor({ actionName: "Convert to named parameters", actionDescription: "Convert to named parameters", newContent: `const c = class { - constructor({ a, b = { x: 1 } }: { a: number; b?: { x: number; }; }) {} + constructor({ a, b = { x: 1 } }: { a: number; b?: { x: number; }; }) { } } var x = new c({ a: 2 });` }); diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters17.ts b/tests/cases/fourslash/refactorConvertToNamedParameters17.ts index 5af97ca694a..7888c33f4e2 100644 --- a/tests/cases/fourslash/refactorConvertToNamedParameters17.ts +++ b/tests/cases/fourslash/refactorConvertToNamedParameters17.ts @@ -11,7 +11,7 @@ edit.applyRefactor({ actionName: "Convert to named parameters", actionDescription: "Convert to named parameters", newContent: `function foo({ t, s }: { t: T; s: S; }) { - return s; + return s; } foo({ t: "a", s: "b" });` }); \ No newline at end of file diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters5.ts b/tests/cases/fourslash/refactorConvertToNamedParameters5.ts index 8b8958bc674..f84e0d7b023 100644 --- a/tests/cases/fourslash/refactorConvertToNamedParameters5.ts +++ b/tests/cases/fourslash/refactorConvertToNamedParameters5.ts @@ -7,6 +7,7 @@ ////} ////var foo = new Foo(); ////foo['bar']("a", "b"); +////foo.bar("a", "b"); goTo.select("a", "b"); edit.applyRefactor({ @@ -19,5 +20,6 @@ edit.applyRefactor({ } } var foo = new Foo(); -foo['bar']({ t: "a", s: "b" });` +foo['bar']({ t: "a", s: "b" }); +foo.bar({ t: "a", s: "b" });` }); \ No newline at end of file From 40987ecf4196b83739800d99b28bb9a405f91be5 Mon Sep 17 00:00:00 2001 From: Gabriela Britto Date: Tue, 29 Jan 2019 16:46:20 -0800 Subject: [PATCH 012/149] add tests --- .../refactorConvertToNamedParameters18.ts | 17 +++++++++++++ .../refactorConvertToNamedParameters19.ts | 24 +++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters18.ts create mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters19.ts diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters18.ts b/tests/cases/fourslash/refactorConvertToNamedParameters18.ts new file mode 100644 index 00000000000..069182e20e5 --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToNamedParameters18.ts @@ -0,0 +1,17 @@ +/// + +////function foo(this: void, /*a*/t: string, s: string/*b*/) { +//// return s; +////} +////foo("a", "b"); + +goTo.select("a", "b"); +edit.applyRefactor({ + refactorName: "Convert to named parameters", + actionName: "Convert to named parameters", + actionDescription: "Convert to named parameters", + newContent: `function foo(this: void, { t, s }: { t: string; s: string; }) { + return s; +} +foo({ t: "a", s: "b" });` +}); \ No newline at end of file diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters19.ts b/tests/cases/fourslash/refactorConvertToNamedParameters19.ts new file mode 100644 index 00000000000..b635ce5e379 --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToNamedParameters19.ts @@ -0,0 +1,24 @@ +/// + +////class Foo { +//// /*a*/bar/*b*/(t: string, s: string): string { +//// return s + t; +//// } +////} +////var foo = {}; +////foo['bar']("a", "b"); +/// + +goTo.select("a", "b"); +edit.applyRefactor({ + refactorName: "Convert to named parameters", + actionName: "Convert to named parameters", + actionDescription: "Convert to named parameters", + newContent: `class Foo { + bar({ t, s }: { t: string; s: string; }): string { + return s + t; + } +} +var foo = {}; +foo['bar']("a", "b");` +}); \ No newline at end of file From bf25ba46509d30aff81cb528273d0111e02c2516 Mon Sep 17 00:00:00 2001 From: Gabriela Britto Date: Fri, 1 Feb 2019 13:09:53 -0800 Subject: [PATCH 013/149] Don't refactor if variable declaration has type annotation --- .../refactors/convertToNamedParameters.ts | 30 ++++++++++--------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/src/services/refactors/convertToNamedParameters.ts b/src/services/refactors/convertToNamedParameters.ts index 3e7e2ca91ed..114874397a9 100644 --- a/src/services/refactors/convertToNamedParameters.ts +++ b/src/services/refactors/convertToNamedParameters.ts @@ -34,12 +34,12 @@ namespace ts.refactor.convertToNamedParameters { } function doChange(sourceFile: SourceFile, program: Program, cancellationToken: CancellationToken, host: LanguageServiceHost, changes: textChanges.ChangeTracker, functionDeclaration: ValidFunctionDeclaration): void { - const newParamDeclaration = map(createObjectParameter(functionDeclaration, program, host), node => getSynthesizedDeepClone(node, /*includeTrivia*/ false)); - const newFunctionDeclaration = updateDeclarationParameters(functionDeclaration, createNodeArray(newParamDeclaration)); + const newParamDeclaration = createObjectParameter(functionDeclaration, program, host); + const newFunctionDeclaration = getSynthesizedDeepClone(updateDeclarationParameters(functionDeclaration, createNodeArray(newParamDeclaration)), /*includeTrivia*/ false); changes.replaceNode(sourceFile, functionDeclaration, newFunctionDeclaration); - const nameNode = getFunctionDeclarationName(functionDeclaration); - const functionRefs = FindAllReferences.getReferenceEntriesForNode(-1, nameNode, program, program.getSourceFiles(), cancellationToken); + const nameNodes = getFunctionDeclarationNames(functionDeclaration); + const functionRefs = flatMap(nameNodes, name => FindAllReferences.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken)); const functionCalls = getDirectFunctionCalls(functionRefs); forEach(functionCalls, call => { @@ -124,11 +124,11 @@ namespace ts.refactor.convertToNamedParameters { return !!func.parent.name && isValidParameterNodeArray(func.parameters) && !!func.body && !checker.isImplementationOfOverload(func); } else { - return isVariableDeclaration(func.parent.parent) && isVarConst(func.parent.parent) && isValidParameterNodeArray(func.parameters) && !!func.body && !checker.isImplementationOfOverload(func); + return isVariableDeclaration(func.parent.parent) && !func.parent.parent.type && isVarConst(func.parent.parent) && isValidParameterNodeArray(func.parameters) && !!func.body && !checker.isImplementationOfOverload(func); } case SyntaxKind.FunctionExpression: case SyntaxKind.ArrowFunction: - return isVariableDeclaration(func.parent) && isVarConst(func.parent) && isValidParameterNodeArray(func.parameters); + return isVariableDeclaration(func.parent) && !func.parent.type && isVarConst(func.parent) && isValidParameterNodeArray(func.parameters); } return false; } @@ -217,27 +217,29 @@ namespace ts.refactor.convertToNamedParameters { return getTextOfIdentifierOrLiteral(paramDecl.name); } - function getFunctionDeclarationName(functionDeclaration: ValidFunctionDeclaration): Node { + function getFunctionDeclarationNames(functionDeclaration: ValidFunctionDeclaration): Node[] { switch (functionDeclaration.kind) { case SyntaxKind.FunctionDeclaration: case SyntaxKind.MethodDeclaration: - return functionDeclaration.name; + return [functionDeclaration.name]; case SyntaxKind.Constructor: switch (functionDeclaration.parent.kind) { case SyntaxKind.ClassDeclaration: - return functionDeclaration.parent.name; + return [functionDeclaration, functionDeclaration.parent.name]; case SyntaxKind.ClassExpression: - return functionDeclaration.parent.parent.name; + return [functionDeclaration.parent.parent.name]; default: return Debug.assertNever(functionDeclaration.parent); } case SyntaxKind.ArrowFunction: case SyntaxKind.FunctionExpression: - return functionDeclaration.parent.name; + return [functionDeclaration.parent.name]; } } + type ValidVariableDeclaration = VariableDeclaration & { type: undefined }; + interface ValidConstructor extends ConstructorDeclaration { - parent: (ClassDeclaration & { name: Identifier }) | (ClassExpression & { parent: VariableDeclaration }); + parent: (ClassDeclaration & { name: Identifier }) | (ClassExpression & { parent: ValidVariableDeclaration }); parameters: NodeArray; body: FunctionBody; } @@ -254,12 +256,12 @@ namespace ts.refactor.convertToNamedParameters { } interface ValidFunctionExpression extends FunctionExpression { - parent: VariableDeclaration; + parent: ValidVariableDeclaration; parameters: NodeArray; } interface ValidArrowFunction extends ArrowFunction { - parent: VariableDeclaration; + parent: ValidVariableDeclaration; parameters: NodeArray; } From bde97d1226b730b2ec4454e5317c7e5fb6184bae Mon Sep 17 00:00:00 2001 From: Gabriela Britto Date: Fri, 1 Feb 2019 16:43:44 -0800 Subject: [PATCH 014/149] fix refactor to find super references --- src/services/refactors/convertToNamedParameters.ts | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/services/refactors/convertToNamedParameters.ts b/src/services/refactors/convertToNamedParameters.ts index 114874397a9..cbc66749f50 100644 --- a/src/services/refactors/convertToNamedParameters.ts +++ b/src/services/refactors/convertToNamedParameters.ts @@ -40,7 +40,7 @@ namespace ts.refactor.convertToNamedParameters { const nameNodes = getFunctionDeclarationNames(functionDeclaration); const functionRefs = flatMap(nameNodes, name => FindAllReferences.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken)); - const functionCalls = getDirectFunctionCalls(functionRefs); + const functionCalls = deduplicate(getDirectFunctionCalls(functionRefs), (a, b) => a === b); forEach(functionCalls, call => { if (call.arguments && call.arguments.length) { @@ -223,13 +223,19 @@ namespace ts.refactor.convertToNamedParameters { case SyntaxKind.MethodDeclaration: return [functionDeclaration.name]; case SyntaxKind.Constructor: + const ctrKeyword = findChildOfKind(functionDeclaration, SyntaxKind.ConstructorKeyword, functionDeclaration.getSourceFile()); + let name: Node; switch (functionDeclaration.parent.kind) { case SyntaxKind.ClassDeclaration: - return [functionDeclaration, functionDeclaration.parent.name]; + name = functionDeclaration.parent.name; + break; case SyntaxKind.ClassExpression: - return [functionDeclaration.parent.parent.name]; + name = functionDeclaration.parent.parent.name; + break; default: return Debug.assertNever(functionDeclaration.parent); } + if (ctrKeyword) return [ctrKeyword, name]; + return [name]; case SyntaxKind.ArrowFunction: case SyntaxKind.FunctionExpression: return [functionDeclaration.parent.name]; From abb11550d33265ae91046754e3c1d5890070a144 Mon Sep 17 00:00:00 2001 From: Gabriela Britto Date: Fri, 1 Feb 2019 16:44:22 -0800 Subject: [PATCH 015/149] add more tests --- .../refactorConvertToNamedParameters20.ts | 17 +++++++++++++ .../refactorConvertToNamedParameters21.ts | 25 +++++++++++++++++++ .../refactorConvertToNamedParameters22.ts | 7 ++++++ 3 files changed, 49 insertions(+) create mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters20.ts create mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters21.ts create mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters22.ts diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters20.ts b/tests/cases/fourslash/refactorConvertToNamedParameters20.ts new file mode 100644 index 00000000000..0fb20ec864d --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToNamedParameters20.ts @@ -0,0 +1,17 @@ +/// + +////function foo(/*a*/a: number, b: number/*b*/) { +//// return { bar: () => a + b }; +////} +////var x = foo(1, 2).bar(); + +goTo.select("a", "b"); +edit.applyRefactor({ + refactorName: "Convert to named parameters", + actionName: "Convert to named parameters", + actionDescription: "Convert to named parameters", + newContent: `function foo({ a, b }: { a: number; b: number; }) { + return { bar: () => a + b }; +} +var x = foo({ a: 1, b: 2 }).bar();` +}); \ No newline at end of file diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters21.ts b/tests/cases/fourslash/refactorConvertToNamedParameters21.ts new file mode 100644 index 00000000000..c5d15903ef5 --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToNamedParameters21.ts @@ -0,0 +1,25 @@ +/// + +////class A { +//// constructor(/*a*/a: string, b: string/*b*/) { } +////} +////class B extends A { +//// constructor(a: string, b: string, c: string) { +//// super(a, b); +//// } +////} + +goTo.select("a", "b"); +edit.applyRefactor({ + refactorName: "Convert to named parameters", + actionName: "Convert to named parameters", + actionDescription: "Convert to named parameters", + newContent: `class A { + constructor({ a, b }: { a: string; b: string; }) { } +} +class B extends A { + constructor(a: string, b: string, c: string) { + super({ a: a, b: b }); + } +}` +}); \ No newline at end of file diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters22.ts b/tests/cases/fourslash/refactorConvertToNamedParameters22.ts new file mode 100644 index 00000000000..05a0f6f54fa --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToNamedParameters22.ts @@ -0,0 +1,7 @@ +/// + +////const foo: (a: number, b: number) => number = /*a*/(a: number, b: number)/*b*/ => a + b; +////foo(1, 2); + +goTo.select("a", "b"); +verify.not.refactorAvailable("Convert to named parameters"); From 674800f25e00ecc0b0ace8c1cfe33f2638624ac9 Mon Sep 17 00:00:00 2001 From: Gabriela Britto Date: Mon, 4 Feb 2019 12:52:27 -0800 Subject: [PATCH 016/149] implement refactor for functions with a rest parameter --- .../refactors/convertToNamedParameters.ts | 63 +++++++++++-------- 1 file changed, 38 insertions(+), 25 deletions(-) diff --git a/src/services/refactors/convertToNamedParameters.ts b/src/services/refactors/convertToNamedParameters.ts index cbc66749f50..0609578c869 100644 --- a/src/services/refactors/convertToNamedParameters.ts +++ b/src/services/refactors/convertToNamedParameters.ts @@ -44,7 +44,7 @@ namespace ts.refactor.convertToNamedParameters { forEach(functionCalls, call => { if (call.arguments && call.arguments.length) { - const newArguments = getSynthesizedDeepClone(createArgumentObject(functionDeclaration, call)); + const newArguments = getSynthesizedDeepClone(createArgumentObject(functionDeclaration, call.arguments)); changes.replaceNodeRange(getSourceFileOfNode(call), first(call.arguments), last(call.arguments), newArguments); }}); } @@ -55,12 +55,6 @@ namespace ts.refactor.convertToNamedParameters { return updateNode(newDeclaration, declaration); } - function createArgumentObject(func: ValidFunctionDeclaration, funcCall: CallExpression | NewExpression): ObjectLiteralExpression { - const parameters = getRefactorableParameters(func.parameters); - const properties = map(funcCall.arguments, (arg, i) => createPropertyAssignment(getParameterName(parameters[i]), arg)); - return createObjectLiteral(properties, /*multiLine*/ false); - } - function getDirectFunctionCalls(referenceEntries: ReadonlyArray | undefined): ReadonlyArray { return mapDefined(referenceEntries, (entry) => { if (entry.kind !== FindAllReferences.EntryKind.Span && entry.node.parent) { @@ -109,26 +103,26 @@ namespace ts.refactor.convertToNamedParameters { function getFunctionDeclarationAtPosition(file: SourceFile, startPosition: number, checker: TypeChecker): ValidFunctionDeclaration | undefined { const node = getTokenAtPosition(file, startPosition); - const func = getContainingFunction(node); - if (!func || !isValidFunctionDeclaration(func, checker) || !rangeContainsRange(func, node) || (func.body && rangeContainsRange(func.body, node))) return undefined; - return func; + const functionDeclaration = getContainingFunction(node); + if (!functionDeclaration || !isValidFunctionDeclaration(functionDeclaration, checker) || !rangeContainsRange(functionDeclaration, node) || (functionDeclaration.body && rangeContainsRange(functionDeclaration.body, node))) return undefined; + return functionDeclaration; } - function isValidFunctionDeclaration(func: SignatureDeclaration, checker: TypeChecker): func is ValidFunctionDeclaration { - switch (func.kind) { + function isValidFunctionDeclaration(functionDeclaration: SignatureDeclaration, checker: TypeChecker): functionDeclaration is ValidFunctionDeclaration { + switch (functionDeclaration.kind) { case SyntaxKind.FunctionDeclaration: case SyntaxKind.MethodDeclaration: - return !!func.name && isPropertyName(func.name) && isValidParameterNodeArray(func.parameters) && !!func.body && !checker.isImplementationOfOverload(func); + return !!functionDeclaration.name && isPropertyName(functionDeclaration.name) && isValidParameterNodeArray(functionDeclaration.parameters) && !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration); case SyntaxKind.Constructor: - if (isClassDeclaration(func.parent)) { - return !!func.parent.name && isValidParameterNodeArray(func.parameters) && !!func.body && !checker.isImplementationOfOverload(func); + if (isClassDeclaration(functionDeclaration.parent)) { + return !!functionDeclaration.parent.name && isValidParameterNodeArray(functionDeclaration.parameters) && !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration); } else { - return isVariableDeclaration(func.parent.parent) && !func.parent.parent.type && isVarConst(func.parent.parent) && isValidParameterNodeArray(func.parameters) && !!func.body && !checker.isImplementationOfOverload(func); + return isVariableDeclaration(functionDeclaration.parent.parent) && !functionDeclaration.parent.parent.type && isVarConst(functionDeclaration.parent.parent) && isValidParameterNodeArray(functionDeclaration.parameters) && !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration); } case SyntaxKind.FunctionExpression: case SyntaxKind.ArrowFunction: - return isVariableDeclaration(func.parent) && !func.parent.type && isVarConst(func.parent) && isValidParameterNodeArray(func.parameters); + return isVariableDeclaration(functionDeclaration.parent) && !functionDeclaration.parent.type && isVarConst(functionDeclaration.parent) && isValidParameterNodeArray(functionDeclaration.parameters); } return false; } @@ -138,7 +132,7 @@ namespace ts.refactor.convertToNamedParameters { } function isValidParameterDeclaration(paramDecl: ParameterDeclaration): paramDecl is ValidParameterDeclaration { - return !paramDecl.modifiers && !paramDecl.dotDotDotToken && isIdentifier(paramDecl.name); + return !paramDecl.modifiers && isIdentifier(paramDecl.name); } function hasThisParameter(parameters: NodeArray): boolean { @@ -159,6 +153,21 @@ namespace ts.refactor.convertToNamedParameters { return parameters; } + function createArgumentObject(functionDeclaration: ValidFunctionDeclaration, args: NodeArray): ObjectLiteralExpression { + const parameters = getRefactorableParameters(functionDeclaration.parameters); + const hasRestParameter = isRestParameter(last(parameters)); + const nonRestArguments = hasRestParameter ? args.slice(0, parameters.length - 1) : args; + const properties = map(nonRestArguments, (arg, i) => createPropertyAssignment(getParameterName(parameters[i]), arg)); + + if (hasRestParameter && args.length >= parameters.length) { + const restArguments = args.slice(parameters.length - 1); + const restProperty = createPropertyAssignment(getParameterName(last(parameters)), createArrayLiteral(restArguments)); + properties.push(restProperty); + } + + return createObjectLiteral(properties, /*multiLine*/ false); + } + function createObjectParameter(functionDeclaration: ValidFunctionDeclaration, program: Program, host: LanguageServiceHost): NodeArray { const refactorableParameters = getRefactorableParameters(functionDeclaration.parameters); const bindingElements = map( @@ -168,7 +177,7 @@ namespace ts.refactor.convertToNamedParameters { /*dotDotDotToken*/ undefined, /*propertyName*/ undefined, getParameterName(paramDecl), - paramDecl.initializer); }); + isRestParameter(paramDecl) ? createArrayLiteral() : paramDecl.initializer); }); const paramName = createObjectBindingPattern(bindingElements); const paramType = createParamTypeNode(refactorableParameters); @@ -199,18 +208,23 @@ namespace ts.refactor.convertToNamedParameters { function createPropertySignatureFromParameterDeclaration(paramDeclaration: ValidParameterDeclaration): PropertySignature { let paramType = paramDeclaration.type; - if (paramDeclaration.initializer && !paramType) { - const checker = program.getTypeChecker(); - const type = checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(paramDeclaration.initializer)); - paramType = getTypeNodeIfAccessible(type, paramDeclaration, program, host); + if (!paramType && (paramDeclaration.initializer || isRestParameter(paramDeclaration))) { + paramType = getTypeNode(paramDeclaration); } + return createPropertySignature( /*modifiers*/ undefined, paramDeclaration.name, - paramDeclaration.initializer ? createToken(SyntaxKind.QuestionToken) : paramDeclaration.questionToken, + paramDeclaration.initializer || isRestParameter(paramDeclaration) ? createToken(SyntaxKind.QuestionToken) : paramDeclaration.questionToken, paramType, /*initializer*/ undefined); } + + function getTypeNode(node: Node): TypeNode | undefined { + const checker = program.getTypeChecker(); + const type = checker.getTypeAtLocation(node); + return getTypeNodeIfAccessible(type, node, program, host); + } } function getParameterName(paramDecl: ValidParameterDeclaration): string { @@ -275,7 +289,6 @@ namespace ts.refactor.convertToNamedParameters { interface ValidParameterDeclaration extends ParameterDeclaration { name: Identifier; - dotDotDotToken: undefined; modifiers: undefined; } } \ No newline at end of file From 1d1c82095ce9abef011caa521dcf0e6222a05c62 Mon Sep 17 00:00:00 2001 From: Gabriela Britto Date: Mon, 4 Feb 2019 12:53:02 -0800 Subject: [PATCH 017/149] add tests for rest parameters --- .../refactorConvertToNamedParameters23.ts | 15 +++++++++++++++ .../refactorConvertToNamedParameters24.ts | 15 +++++++++++++++ 2 files changed, 30 insertions(+) create mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters23.ts create mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters24.ts diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters23.ts b/tests/cases/fourslash/refactorConvertToNamedParameters23.ts new file mode 100644 index 00000000000..36ed5084fe2 --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToNamedParameters23.ts @@ -0,0 +1,15 @@ +/// + +////function log(/*a*/a: number, b: number, ...args/*b*/) { } +////let l = log(-1, -2, 3, 4, 5); +////let k = log(1, 2); + +goTo.select("a", "b"); +edit.applyRefactor({ + refactorName: "Convert to named parameters", + actionName: "Convert to named parameters", + actionDescription: "Convert to named parameters", + newContent: `function log({ a, b, args = [] }: { a: number; b: number; args?: any[]; }) { } +let l = log({ a: -1, b: -2, args: [3, 4, 5] }); +let k = log({ a: 1, b: 2 });` +}); \ No newline at end of file diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters24.ts b/tests/cases/fourslash/refactorConvertToNamedParameters24.ts new file mode 100644 index 00000000000..34e0331f466 --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToNamedParameters24.ts @@ -0,0 +1,15 @@ +/// + +////function /*a*/buildName/*b*/(firstName: string, middleName?: string, ...restOfName: string[]) { } +////let employeeName = buildName("Joseph", "Samuel", "Lucas", "MacKinzie"); +////let myName = buildName("Joseph"); + +goTo.select("a", "b"); +edit.applyRefactor({ + refactorName: "Convert to named parameters", + actionName: "Convert to named parameters", + actionDescription: "Convert to named parameters", + newContent: `function buildName({ firstName, middleName, restOfName = [] }: { firstName: string; middleName?: string; restOfName?: string[]; }) { } +let employeeName = buildName({ firstName: "Joseph", middleName: "Samuel", restOfName: ["Lucas", "MacKinzie"] }); +let myName = buildName({ firstName: "Joseph" });` +}); \ No newline at end of file From 52a9cfb0a9de3f0c0f36a77bb976330a0a57f6df Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Wed, 6 Feb 2019 14:23:49 -0800 Subject: [PATCH 018/149] Infer to partially homomorphic mapped types (such as Pick) --- src/compiler/checker.ts | 45 ++++++++++++++++++++++++++--------------- 1 file changed, 29 insertions(+), 16 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index ce06e84b2fd..aa5007065fc 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -14570,11 +14570,24 @@ namespace ts { return undefined; } - function inferFromMappedTypeConstraint(source: Type, target: Type, constraintType: Type): boolean { + function inferToHomomorphicMappedType(source: Type, target: MappedType, constraintType: IndexType) { + const inference = getInferenceInfoForType(constraintType.type); + if (inference && !inference.isFixed) { + const inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType); + if (inferredType) { + const savePriority = priority; + priority |= InferencePriority.HomomorphicMappedType; + inferFromTypes(inferredType, inference.typeParameter); + priority = savePriority; + } + } + } + + function inferToMappedType(source: Type, target: MappedType, constraintType: Type): boolean { if (constraintType.flags & TypeFlags.Union) { let result = false; for (const type of (constraintType as UnionType).types) { - result = inferFromMappedTypeConstraint(source, target, type) || result; + result = inferToMappedType(source, target, type) || result; } return result; } @@ -14583,31 +14596,31 @@ namespace ts { // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source // type and then make a secondary inference from that type to T. We make a secondary inference // such that direct inferences to T get priority over inferences to Partial, for example. - const inference = getInferenceInfoForType((constraintType).type); - if (inference && !inference.isFixed) { - const inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType as IndexType); - if (inferredType) { - const savePriority = priority; - priority |= InferencePriority.HomomorphicMappedType; - inferFromTypes(inferredType, inference.typeParameter); - priority = savePriority; - } - } + inferToHomomorphicMappedType(source, target, constraintType); return true; } if (constraintType.flags & TypeFlags.TypeParameter) { - // We're inferring from some source type S to a mapped type { [P in T]: X }, where T is a type - // parameter. Infer from 'keyof S' to T and infer from a union of each property type in S to X. + // We're inferring from some source type S to a mapped type { [P in K]: X }, where K is a type + // parameter. First infer from 'keyof S' to K. const savePriority = priority; priority |= InferencePriority.MappedTypeConstraint; inferFromTypes(getIndexType(source), constraintType); priority = savePriority; + // If K is constrained to an index type keyof T, where T is a type parameter, proceed to make + // the same inferences as we would for a homomorphic mapped type { [P in keyof T]: X } (this + // enables us to make meaningful inferences when the target is a Pick). Otherwise, infer + // from a union of the property types in the source to the template type X. + const extendedConstraint = getConstraintOfType(constraintType); + if (extendedConstraint && extendedConstraint.flags & TypeFlags.Index) { + inferToHomomorphicMappedType(source, target, extendedConstraint); + return true; + } const valueTypes = compact([ getIndexTypeOfType(source, IndexKind.String), getIndexTypeOfType(source, IndexKind.Number), ...map(getPropertiesOfType(source), getTypeOfSymbol) ]); - inferFromTypes(getUnionType(valueTypes), getTemplateTypeFromMappedType(target)); + inferFromTypes(getUnionType(valueTypes), getTemplateTypeFromMappedType(target)); return true; } return false; @@ -14622,7 +14635,7 @@ namespace ts { } if (getObjectFlags(target) & ObjectFlags.Mapped) { const constraintType = getConstraintTypeFromMappedType(target); - if (inferFromMappedTypeConstraint(source, target, constraintType)) { + if (inferToMappedType(source, target, constraintType)) { return; } } From 18b2b55387a0e140d7ec5366a6821052bd46dbbf Mon Sep 17 00:00:00 2001 From: Gabriela Britto Date: Wed, 6 Feb 2019 15:38:59 -0800 Subject: [PATCH 019/149] add option to suppressLeadingAndTrailingTrivia non recursively --- src/services/utilities.ts | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/src/services/utilities.ts b/src/services/utilities.ts index 0574afe34bd..2b6d0acde88 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -1753,23 +1753,33 @@ namespace ts { /** * Sets EmitFlags to suppress leading and trailing trivia on the node. */ - export function suppressLeadingAndTrailingTrivia(node: Node) { - suppressLeadingTrivia(node); - suppressTrailingTrivia(node); + export function suppressLeadingAndTrailingTrivia(node: Node, recursive = true) { + suppressLeadingTrivia(node, recursive); + suppressTrailingTrivia(node, recursive); } /** * Sets EmitFlags to suppress leading trivia on the node. */ - export function suppressLeadingTrivia(node: Node) { - addEmitFlagsRecursively(node, EmitFlags.NoLeadingComments, getFirstChild); + export function suppressLeadingTrivia(node: Node, recursive = true) { + if (recursive) { + addEmitFlagsRecursively(node, EmitFlags.NoLeadingComments, getFirstChild); + } + else { + addEmitFlags(node, EmitFlags.NoLeadingComments); + } } /** * Sets EmitFlags to suppress trailing trivia on the node. */ - export function suppressTrailingTrivia(node: Node) { - addEmitFlagsRecursively(node, EmitFlags.NoTrailingComments, getLastChild); + export function suppressTrailingTrivia(node: Node, recursive = true) { + if (recursive) { + addEmitFlagsRecursively(node, EmitFlags.NoTrailingComments, getLastChild); + } + else { + addEmitFlags(node, EmitFlags.NoTrailingComments); + } } function addEmitFlagsRecursively(node: Node, flag: EmitFlags, getChild: (n: Node) => Node | undefined) { From b87392c22c7a6ca5fb53b24243cb0b6f5b30ef7b Mon Sep 17 00:00:00 2001 From: Gabriela Britto Date: Wed, 6 Feb 2019 15:40:58 -0800 Subject: [PATCH 020/149] fix duplication of leading and trailing comments on refactored function --- .../refactors/convertToNamedParameters.ts | 46 +++++++++++-------- 1 file changed, 26 insertions(+), 20 deletions(-) diff --git a/src/services/refactors/convertToNamedParameters.ts b/src/services/refactors/convertToNamedParameters.ts index 0609578c869..c414f2b0a8f 100644 --- a/src/services/refactors/convertToNamedParameters.ts +++ b/src/services/refactors/convertToNamedParameters.ts @@ -5,6 +5,7 @@ namespace ts.refactor.convertToNamedParameters { const actionNameNamedParameters = "Convert to named parameters"; const actionDescriptionNamedParameters = "Convert to named parameters"; const minimumParameterLength = 1; + let refactorSucceeded = true; registerRefactor(refactorName, { getEditsForAction, getAvailableActions }); @@ -26,25 +27,27 @@ namespace ts.refactor.convertToNamedParameters { function getEditsForAction(context: RefactorContext, actionName: string): RefactorEditInfo | undefined { Debug.assert(actionName === actionNameNamedParameters); const { file, startPosition, program, cancellationToken, host } = context; - const func = getFunctionDeclarationAtPosition(file, startPosition, program.getTypeChecker()); - if (!func || !cancellationToken) return undefined; + const functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, program.getTypeChecker()); + if (!functionDeclaration || !cancellationToken) return undefined; - const edits = textChanges.ChangeTracker.with(context, t => doChange(file, program, cancellationToken, host, t, func)); - return { renameFilename: undefined, renameLocation: undefined, edits }; + const edits = textChanges.ChangeTracker.with(context, t => doChange(file, program, cancellationToken, host, t, functionDeclaration)); + return refactorSucceeded ? { renameFilename: undefined, renameLocation: undefined, edits } : undefined; } function doChange(sourceFile: SourceFile, program: Program, cancellationToken: CancellationToken, host: LanguageServiceHost, changes: textChanges.ChangeTracker, functionDeclaration: ValidFunctionDeclaration): void { - const newParamDeclaration = createObjectParameter(functionDeclaration, program, host); - const newFunctionDeclaration = getSynthesizedDeepClone(updateDeclarationParameters(functionDeclaration, createNodeArray(newParamDeclaration)), /*includeTrivia*/ false); + const newParamDeclaration = map(createNewParameters(functionDeclaration, program, host), param => getSynthesizedDeepClone(param, /*includeTrivia*/ true)); + const newFunctionDeclaration = updateDeclarationParameters(functionDeclaration, createNodeArray(newParamDeclaration)); + suppressLeadingAndTrailingTrivia(newFunctionDeclaration, /*recursive*/ false); changes.replaceNode(sourceFile, functionDeclaration, newFunctionDeclaration); const nameNodes = getFunctionDeclarationNames(functionDeclaration); const functionRefs = flatMap(nameNodes, name => FindAllReferences.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken)); const functionCalls = deduplicate(getDirectFunctionCalls(functionRefs), (a, b) => a === b); + refactorSucceeded = true; // TODO: check if a bad reference was found forEach(functionCalls, call => { if (call.arguments && call.arguments.length) { - const newArguments = getSynthesizedDeepClone(createArgumentObject(functionDeclaration, call.arguments)); + const newArguments = getSynthesizedDeepClone(createNewArguments(functionDeclaration, call.arguments), /*includeTrivia*/ true); changes.replaceNodeRange(getSourceFileOfNode(call), first(call.arguments), last(call.arguments), newArguments); }}); } @@ -125,14 +128,14 @@ namespace ts.refactor.convertToNamedParameters { return isVariableDeclaration(functionDeclaration.parent) && !functionDeclaration.parent.type && isVarConst(functionDeclaration.parent) && isValidParameterNodeArray(functionDeclaration.parameters); } return false; - } - function isValidParameterNodeArray(parameters: NodeArray): boolean { - return parameters && getRefactorableParametersLength(parameters) > minimumParameterLength && every(parameters, isValidParameterDeclaration); - } + function isValidParameterNodeArray(parameters: NodeArray): parameters is ValidParameterNodeArray { + return parameters && getRefactorableParametersLength(parameters) > minimumParameterLength && every(parameters, isValidParameterDeclaration); + } - function isValidParameterDeclaration(paramDecl: ParameterDeclaration): paramDecl is ValidParameterDeclaration { - return !paramDecl.modifiers && isIdentifier(paramDecl.name); + function isValidParameterDeclaration(paramDeclaration: ParameterDeclaration): paramDeclaration is ValidParameterDeclaration { + return !paramDeclaration.modifiers && isIdentifier(paramDeclaration.name); + } } function hasThisParameter(parameters: NodeArray): boolean { @@ -153,7 +156,7 @@ namespace ts.refactor.convertToNamedParameters { return parameters; } - function createArgumentObject(functionDeclaration: ValidFunctionDeclaration, args: NodeArray): ObjectLiteralExpression { + function createNewArguments(functionDeclaration: ValidFunctionDeclaration, args: NodeArray): ObjectLiteralExpression { const parameters = getRefactorableParameters(functionDeclaration.parameters); const hasRestParameter = isRestParameter(last(parameters)); const nonRestArguments = hasRestParameter ? args.slice(0, parameters.length - 1) : args; @@ -168,16 +171,17 @@ namespace ts.refactor.convertToNamedParameters { return createObjectLiteral(properties, /*multiLine*/ false); } - function createObjectParameter(functionDeclaration: ValidFunctionDeclaration, program: Program, host: LanguageServiceHost): NodeArray { + function createNewParameters(functionDeclaration: ValidFunctionDeclaration, program: Program, host: LanguageServiceHost): NodeArray { const refactorableParameters = getRefactorableParameters(functionDeclaration.parameters); const bindingElements = map( refactorableParameters, paramDecl => { - return createBindingElement( + const element = createBindingElement( /*dotDotDotToken*/ undefined, /*propertyName*/ undefined, getParameterName(paramDecl), - isRestParameter(paramDecl) ? createArrayLiteral() : paramDecl.initializer); }); + isRestParameter(paramDecl) ? createArrayLiteral() : paramDecl.initializer); + return element; }); const paramName = createObjectBindingPattern(bindingElements); const paramType = createParamTypeNode(refactorableParameters); @@ -214,7 +218,7 @@ namespace ts.refactor.convertToNamedParameters { return createPropertySignature( /*modifiers*/ undefined, - paramDeclaration.name, + getParameterName(paramDeclaration), paramDeclaration.initializer || isRestParameter(paramDeclaration) ? createToken(SyntaxKind.QuestionToken) : paramDeclaration.questionToken, paramType, /*initializer*/ undefined); @@ -227,8 +231,8 @@ namespace ts.refactor.convertToNamedParameters { } } - function getParameterName(paramDecl: ValidParameterDeclaration): string { - return getTextOfIdentifierOrLiteral(paramDecl.name); + function getParameterName(paramDeclaration: ValidParameterDeclaration) { + return getTextOfIdentifierOrLiteral(paramDeclaration.name); } function getFunctionDeclarationNames(functionDeclaration: ValidFunctionDeclaration): Node[] { @@ -256,6 +260,8 @@ namespace ts.refactor.convertToNamedParameters { } } + type ValidParameterNodeArray = NodeArray; + type ValidVariableDeclaration = VariableDeclaration & { type: undefined }; interface ValidConstructor extends ConstructorDeclaration { From 62c62f4f87bfcf96e3f0e0500b453187b39f3c89 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Wed, 6 Feb 2019 15:41:43 -0800 Subject: [PATCH 021/149] Add tests --- .../mapped/isomorphicMappedTypeInference.ts | 25 ++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/tests/cases/conformance/types/mapped/isomorphicMappedTypeInference.ts b/tests/cases/conformance/types/mapped/isomorphicMappedTypeInference.ts index 14bb765a840..534d50c367e 100644 --- a/tests/cases/conformance/types/mapped/isomorphicMappedTypeInference.ts +++ b/tests/cases/conformance/types/mapped/isomorphicMappedTypeInference.ts @@ -152,4 +152,27 @@ var g2 = applySpec({ foo: { bar: { baz: (x: any) => true } } }); const foo = (object: T, partial: Partial) => object; let o = {a: 5, b: 7}; foo(o, {b: 9}); -o = foo(o, {b: 9}); \ No newline at end of file +o = foo(o, {b: 9}); + +// Inferring to { [P in K]: X }, where K extends keyof T, produces same inferences as +// inferring to { [P in keyof T]: X }. + +declare function f20(obj: Pick): T; +declare function f21(obj: Pick): K; +declare function f22(obj: Boxified>): T; + +let x0 = f20({ foo: 42, bar: "hello" }); +let x1 = f21({ foo: 42, bar: "hello" }); +let x2 = f22({ foo: { value: 42} , bar: { value: "hello" } }); + +// Repro from #29765 + +function getProps(obj: T, list: K[]): Pick { + return {} as any; +} + +const myAny: any = {}; + +const o1 = getProps(myAny, ['foo', 'bar']); + +const o2: { foo: any; bar: any } = getProps(myAny, ['foo', 'bar']); From 262e3c1ae294cef6e1075fa53a4d60481c700494 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Wed, 6 Feb 2019 15:41:51 -0800 Subject: [PATCH 022/149] Accept new baselines --- .../isomorphicMappedTypeInference.js | 55 +++++++++++- .../isomorphicMappedTypeInference.symbols | 90 +++++++++++++++++++ .../isomorphicMappedTypeInference.types | 85 ++++++++++++++++++ 3 files changed, 229 insertions(+), 1 deletion(-) diff --git a/tests/baselines/reference/isomorphicMappedTypeInference.js b/tests/baselines/reference/isomorphicMappedTypeInference.js index 58912244432..6cfc2ec7350 100644 --- a/tests/baselines/reference/isomorphicMappedTypeInference.js +++ b/tests/baselines/reference/isomorphicMappedTypeInference.js @@ -149,7 +149,31 @@ var g2 = applySpec({ foo: { bar: { baz: (x: any) => true } } }); const foo = (object: T, partial: Partial) => object; let o = {a: 5, b: 7}; foo(o, {b: 9}); -o = foo(o, {b: 9}); +o = foo(o, {b: 9}); + +// Inferring to { [P in K]: X }, where K extends keyof T, produces same inferences as +// inferring to { [P in keyof T]: X }. + +declare function f20(obj: Pick): T; +declare function f21(obj: Pick): K; +declare function f22(obj: Boxified>): T; + +let x0 = f20({ foo: 42, bar: "hello" }); +let x1 = f21({ foo: 42, bar: "hello" }); +let x2 = f22({ foo: { value: 42} , bar: { value: "hello" } }); + +// Repro from #29765 + +function getProps(obj: T, list: K[]): Pick { + return {} as any; +} + +const myAny: any = {}; + +const o1 = getProps(myAny, ['foo', 'bar']); + +const o2: { foo: any; bar: any } = getProps(myAny, ['foo', 'bar']); + //// [isomorphicMappedTypeInference.js] function box(x) { @@ -255,6 +279,16 @@ var foo = function (object, partial) { return object; }; var o = { a: 5, b: 7 }; foo(o, { b: 9 }); o = foo(o, { b: 9 }); +var x0 = f20({ foo: 42, bar: "hello" }); +var x1 = f21({ foo: 42, bar: "hello" }); +var x2 = f22({ foo: { value: 42 }, bar: { value: "hello" } }); +// Repro from #29765 +function getProps(obj, list) { + return {}; +} +var myAny = {}; +var o1 = getProps(myAny, ['foo', 'bar']); +var o2 = getProps(myAny, ['foo', 'bar']); //// [isomorphicMappedTypeInference.d.ts] @@ -323,3 +357,22 @@ declare let o: { a: number; b: number; }; +declare function f20(obj: Pick): T; +declare function f21(obj: Pick): K; +declare function f22(obj: Boxified>): T; +declare let x0: { + foo: number; + bar: string; +}; +declare let x1: "foo" | "bar"; +declare let x2: { + foo: number; + bar: string; +}; +declare function getProps(obj: T, list: K[]): Pick; +declare const myAny: any; +declare const o1: Pick; +declare const o2: { + foo: any; + bar: any; +}; diff --git a/tests/baselines/reference/isomorphicMappedTypeInference.symbols b/tests/baselines/reference/isomorphicMappedTypeInference.symbols index d36ebc7a4a5..6f999f91dc4 100644 --- a/tests/baselines/reference/isomorphicMappedTypeInference.symbols +++ b/tests/baselines/reference/isomorphicMappedTypeInference.symbols @@ -486,3 +486,93 @@ o = foo(o, {b: 9}); >o : Symbol(o, Decl(isomorphicMappedTypeInference.ts, 148, 3)) >b : Symbol(b, Decl(isomorphicMappedTypeInference.ts, 150, 12)) +// Inferring to { [P in K]: X }, where K extends keyof T, produces same inferences as +// inferring to { [P in keyof T]: X }. + +declare function f20(obj: Pick): T; +>f20 : Symbol(f20, Decl(isomorphicMappedTypeInference.ts, 150, 19)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 155, 21)) +>K : Symbol(K, Decl(isomorphicMappedTypeInference.ts, 155, 23)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 155, 21)) +>obj : Symbol(obj, Decl(isomorphicMappedTypeInference.ts, 155, 43)) +>Pick : Symbol(Pick, Decl(lib.es5.d.ts, --, --)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 155, 21)) +>K : Symbol(K, Decl(isomorphicMappedTypeInference.ts, 155, 23)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 155, 21)) + +declare function f21(obj: Pick): K; +>f21 : Symbol(f21, Decl(isomorphicMappedTypeInference.ts, 155, 63)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 156, 21)) +>K : Symbol(K, Decl(isomorphicMappedTypeInference.ts, 156, 23)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 156, 21)) +>obj : Symbol(obj, Decl(isomorphicMappedTypeInference.ts, 156, 43)) +>Pick : Symbol(Pick, Decl(lib.es5.d.ts, --, --)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 156, 21)) +>K : Symbol(K, Decl(isomorphicMappedTypeInference.ts, 156, 23)) +>K : Symbol(K, Decl(isomorphicMappedTypeInference.ts, 156, 23)) + +declare function f22(obj: Boxified>): T; +>f22 : Symbol(f22, Decl(isomorphicMappedTypeInference.ts, 156, 63)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 157, 21)) +>K : Symbol(K, Decl(isomorphicMappedTypeInference.ts, 157, 23)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 157, 21)) +>obj : Symbol(obj, Decl(isomorphicMappedTypeInference.ts, 157, 43)) +>Boxified : Symbol(Boxified, Decl(isomorphicMappedTypeInference.ts, 2, 1)) +>Pick : Symbol(Pick, Decl(lib.es5.d.ts, --, --)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 157, 21)) +>K : Symbol(K, Decl(isomorphicMappedTypeInference.ts, 157, 23)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 157, 21)) + +let x0 = f20({ foo: 42, bar: "hello" }); +>x0 : Symbol(x0, Decl(isomorphicMappedTypeInference.ts, 159, 3)) +>f20 : Symbol(f20, Decl(isomorphicMappedTypeInference.ts, 150, 19)) +>foo : Symbol(foo, Decl(isomorphicMappedTypeInference.ts, 159, 14)) +>bar : Symbol(bar, Decl(isomorphicMappedTypeInference.ts, 159, 23)) + +let x1 = f21({ foo: 42, bar: "hello" }); +>x1 : Symbol(x1, Decl(isomorphicMappedTypeInference.ts, 160, 3)) +>f21 : Symbol(f21, Decl(isomorphicMappedTypeInference.ts, 155, 63)) +>foo : Symbol(foo, Decl(isomorphicMappedTypeInference.ts, 160, 14)) +>bar : Symbol(bar, Decl(isomorphicMappedTypeInference.ts, 160, 23)) + +let x2 = f22({ foo: { value: 42} , bar: { value: "hello" } }); +>x2 : Symbol(x2, Decl(isomorphicMappedTypeInference.ts, 161, 3)) +>f22 : Symbol(f22, Decl(isomorphicMappedTypeInference.ts, 156, 63)) +>foo : Symbol(foo, Decl(isomorphicMappedTypeInference.ts, 161, 14)) +>value : Symbol(value, Decl(isomorphicMappedTypeInference.ts, 161, 21)) +>bar : Symbol(bar, Decl(isomorphicMappedTypeInference.ts, 161, 34)) +>value : Symbol(value, Decl(isomorphicMappedTypeInference.ts, 161, 41)) + +// Repro from #29765 + +function getProps(obj: T, list: K[]): Pick { +>getProps : Symbol(getProps, Decl(isomorphicMappedTypeInference.ts, 161, 62)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 165, 18)) +>K : Symbol(K, Decl(isomorphicMappedTypeInference.ts, 165, 20)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 165, 18)) +>obj : Symbol(obj, Decl(isomorphicMappedTypeInference.ts, 165, 40)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 165, 18)) +>list : Symbol(list, Decl(isomorphicMappedTypeInference.ts, 165, 47)) +>K : Symbol(K, Decl(isomorphicMappedTypeInference.ts, 165, 20)) +>Pick : Symbol(Pick, Decl(lib.es5.d.ts, --, --)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 165, 18)) +>K : Symbol(K, Decl(isomorphicMappedTypeInference.ts, 165, 20)) + + return {} as any; +} + +const myAny: any = {}; +>myAny : Symbol(myAny, Decl(isomorphicMappedTypeInference.ts, 169, 5)) + +const o1 = getProps(myAny, ['foo', 'bar']); +>o1 : Symbol(o1, Decl(isomorphicMappedTypeInference.ts, 171, 5)) +>getProps : Symbol(getProps, Decl(isomorphicMappedTypeInference.ts, 161, 62)) +>myAny : Symbol(myAny, Decl(isomorphicMappedTypeInference.ts, 169, 5)) + +const o2: { foo: any; bar: any } = getProps(myAny, ['foo', 'bar']); +>o2 : Symbol(o2, Decl(isomorphicMappedTypeInference.ts, 173, 5)) +>foo : Symbol(foo, Decl(isomorphicMappedTypeInference.ts, 173, 11)) +>bar : Symbol(bar, Decl(isomorphicMappedTypeInference.ts, 173, 21)) +>getProps : Symbol(getProps, Decl(isomorphicMappedTypeInference.ts, 161, 62)) +>myAny : Symbol(myAny, Decl(isomorphicMappedTypeInference.ts, 169, 5)) + diff --git a/tests/baselines/reference/isomorphicMappedTypeInference.types b/tests/baselines/reference/isomorphicMappedTypeInference.types index 4488fa27daf..b37175b5eed 100644 --- a/tests/baselines/reference/isomorphicMappedTypeInference.types +++ b/tests/baselines/reference/isomorphicMappedTypeInference.types @@ -507,3 +507,88 @@ o = foo(o, {b: 9}); >b : number >9 : 9 +// Inferring to { [P in K]: X }, where K extends keyof T, produces same inferences as +// inferring to { [P in keyof T]: X }. + +declare function f20(obj: Pick): T; +>f20 : (obj: Pick) => T +>obj : Pick + +declare function f21(obj: Pick): K; +>f21 : (obj: Pick) => K +>obj : Pick + +declare function f22(obj: Boxified>): T; +>f22 : (obj: Boxified>) => T +>obj : Boxified> + +let x0 = f20({ foo: 42, bar: "hello" }); +>x0 : { foo: number; bar: string; } +>f20({ foo: 42, bar: "hello" }) : { foo: number; bar: string; } +>f20 : (obj: Pick) => T +>{ foo: 42, bar: "hello" } : { foo: number; bar: string; } +>foo : number +>42 : 42 +>bar : string +>"hello" : "hello" + +let x1 = f21({ foo: 42, bar: "hello" }); +>x1 : "foo" | "bar" +>f21({ foo: 42, bar: "hello" }) : "foo" | "bar" +>f21 : (obj: Pick) => K +>{ foo: 42, bar: "hello" } : { foo: number; bar: string; } +>foo : number +>42 : 42 +>bar : string +>"hello" : "hello" + +let x2 = f22({ foo: { value: 42} , bar: { value: "hello" } }); +>x2 : { foo: number; bar: string; } +>f22({ foo: { value: 42} , bar: { value: "hello" } }) : { foo: number; bar: string; } +>f22 : (obj: Boxified>) => T +>{ foo: { value: 42} , bar: { value: "hello" } } : { foo: { value: number; }; bar: { value: string; }; } +>foo : { value: number; } +>{ value: 42} : { value: number; } +>value : number +>42 : 42 +>bar : { value: string; } +>{ value: "hello" } : { value: string; } +>value : string +>"hello" : "hello" + +// Repro from #29765 + +function getProps(obj: T, list: K[]): Pick { +>getProps : (obj: T, list: K[]) => Pick +>obj : T +>list : K[] + + return {} as any; +>{} as any : any +>{} : {} +} + +const myAny: any = {}; +>myAny : any +>{} : {} + +const o1 = getProps(myAny, ['foo', 'bar']); +>o1 : Pick +>getProps(myAny, ['foo', 'bar']) : Pick +>getProps : (obj: T, list: K[]) => Pick +>myAny : any +>['foo', 'bar'] : ("foo" | "bar")[] +>'foo' : "foo" +>'bar' : "bar" + +const o2: { foo: any; bar: any } = getProps(myAny, ['foo', 'bar']); +>o2 : { foo: any; bar: any; } +>foo : any +>bar : any +>getProps(myAny, ['foo', 'bar']) : Pick +>getProps : (obj: T, list: K[]) => Pick +>myAny : any +>['foo', 'bar'] : ("foo" | "bar")[] +>'foo' : "foo" +>'bar' : "bar" + From 7d86fda151d48bfe6802755a0f7e407f63b747cd Mon Sep 17 00:00:00 2001 From: Gabriela Britto Date: Wed, 6 Feb 2019 16:06:46 -0800 Subject: [PATCH 023/149] fix hasThisParameter to check for parameters length --- src/services/refactors/convertToNamedParameters.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/services/refactors/convertToNamedParameters.ts b/src/services/refactors/convertToNamedParameters.ts index c414f2b0a8f..16716bed106 100644 --- a/src/services/refactors/convertToNamedParameters.ts +++ b/src/services/refactors/convertToNamedParameters.ts @@ -139,7 +139,7 @@ namespace ts.refactor.convertToNamedParameters { } function hasThisParameter(parameters: NodeArray): boolean { - return isThis(parameters[0].name); + return parameters.length > 0 && isThis(parameters[0].name); } function getRefactorableParametersLength(parameters: NodeArray): number { From 582526929b0b8e44fc28579083038520d9c55d7b Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Thu, 7 Feb 2019 10:27:50 +0900 Subject: [PATCH 024/149] restore flags --- src/compiler/types.ts | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/compiler/types.ts b/src/compiler/types.ts index a2054243e04..0ea375d0755 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -5046,14 +5046,14 @@ namespace ts { ContainsTypeScript = 1 << 1, ContainsJsx = 1 << 2, ContainsESNext = 1 << 3, - ContainsES2017 = 1 << 5, - ContainsES2016 = 1 << 6, - ES2015 = 1 << 7, - ContainsES2015 = 1 << 8, - Generator = 1 << 9, - ContainsGenerator = 1 << 10, - DestructuringAssignment = 1 << 11, - ContainsDestructuringAssignment = 1 << 12, + ContainsES2017 = 1 << 4, + ContainsES2016 = 1 << 5, + ES2015 = 1 << 6, + ContainsES2015 = 1 << 7, + Generator = 1 << 8, + ContainsGenerator = 1 << 9, + DestructuringAssignment = 1 << 10, + ContainsDestructuringAssignment = 1 << 11, // Markers // - Flags used to indicate that a subtree contains a specific transformation. From 40a4bd0a958a3aaa70b6d209607f3501adf3cdad Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Thu, 7 Feb 2019 10:45:44 +0900 Subject: [PATCH 025/149] revive esnext.symbol --- src/compiler/commandLineParser.ts | 1 + src/testRunner/unittests/config/commandLineParsing.ts | 6 +++--- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index e7db3748d02..676e6e3520b 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -44,6 +44,7 @@ namespace ts { ["es2018.regexp", "lib.es2018.regexp.d.ts"], ["es2019.symbol", "lib.es2019.symbol.d.ts"], ["esnext.array", "lib.esnext.array.d.ts"], + ["esnext.symbol", "lib.es2019.symbol.d.ts"], ["esnext.asynciterable", "lib.esnext.asynciterable.d.ts"], ["esnext.intl", "lib.esnext.intl.d.ts"], ["esnext.bigint", "lib.esnext.bigint.d.ts"] diff --git a/src/testRunner/unittests/config/commandLineParsing.ts b/src/testRunner/unittests/config/commandLineParsing.ts index 8d49fde6e42..a79ebea1c69 100644 --- a/src/testRunner/unittests/config/commandLineParsing.ts +++ b/src/testRunner/unittests/config/commandLineParsing.ts @@ -57,7 +57,7 @@ namespace ts { assertParseResult(["--lib", "es5,invalidOption", "0.ts"], { errors: [{ - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', '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.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.symbol', 'esnext.array', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', '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.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.symbol', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.", category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, file: undefined, @@ -259,7 +259,7 @@ namespace ts { assertParseResult(["--lib", "es5,", "es7", "0.ts"], { errors: [{ - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', '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.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.symbol', 'esnext.array', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', '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.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.symbol', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.", category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, file: undefined, @@ -278,7 +278,7 @@ namespace ts { assertParseResult(["--lib", "es5, ", "es7", "0.ts"], { errors: [{ - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', '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.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.symbol', 'esnext.array', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', '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.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.symbol', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.", category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, file: undefined, From f525a89e87069e8934db097829dc9ff74bf10d3b Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Fri, 8 Feb 2019 00:10:34 +0900 Subject: [PATCH 026/149] Array.prototype.{flat,flatMap} hit stage 4 --- lib/lib.esnext.d.ts | 1 - src/compiler/commandLineParser.ts | 3 ++- src/lib/{esnext.array.d.ts => es2019.array.d.ts} | 0 src/lib/es2019.d.ts | 1 + src/lib/libs.json | 2 +- .../unittests/config/commandLineParsing.ts | 6 +++--- tests/baselines/reference/arrayFlatMap.symbols | 14 +++++++------- tests/cases/compiler/arrayFlatMap.ts | 2 +- 8 files changed, 15 insertions(+), 14 deletions(-) rename src/lib/{esnext.array.d.ts => es2019.array.d.ts} (100%) diff --git a/lib/lib.esnext.d.ts b/lib/lib.esnext.d.ts index f213999684d..59d33ab80f4 100644 --- a/lib/lib.esnext.d.ts +++ b/lib/lib.esnext.d.ts @@ -20,7 +20,6 @@ and limitations under the License. /// /// -/// /// /// /// diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 676e6e3520b..81884b9c75d 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -42,8 +42,9 @@ namespace ts { ["es2018.intl", "lib.es2018.intl.d.ts"], ["es2018.promise", "lib.es2018.promise.d.ts"], ["es2018.regexp", "lib.es2018.regexp.d.ts"], + ["es2019.array", "lib.es2019.array.d.ts"], ["es2019.symbol", "lib.es2019.symbol.d.ts"], - ["esnext.array", "lib.esnext.array.d.ts"], + ["esnext.array", "lib.es2019.array.d.ts"], ["esnext.symbol", "lib.es2019.symbol.d.ts"], ["esnext.asynciterable", "lib.esnext.asynciterable.d.ts"], ["esnext.intl", "lib.esnext.intl.d.ts"], diff --git a/src/lib/esnext.array.d.ts b/src/lib/es2019.array.d.ts similarity index 100% rename from src/lib/esnext.array.d.ts rename to src/lib/es2019.array.d.ts diff --git a/src/lib/es2019.d.ts b/src/lib/es2019.d.ts index 60b8787d587..217d82a219c 100644 --- a/src/lib/es2019.d.ts +++ b/src/lib/es2019.d.ts @@ -1,2 +1,3 @@ /// +/// /// diff --git a/src/lib/libs.json b/src/lib/libs.json index 17b54324e9d..f1afe448f9f 100644 --- a/src/lib/libs.json +++ b/src/lib/libs.json @@ -33,9 +33,9 @@ "es2018.regexp", "es2018.promise", "es2018.intl", + "es2019.array", "es2019.symbol", "esnext.asynciterable", - "esnext.array", "esnext.bigint", "esnext.intl", // Default libraries diff --git a/src/testRunner/unittests/config/commandLineParsing.ts b/src/testRunner/unittests/config/commandLineParsing.ts index a79ebea1c69..387715fe82a 100644 --- a/src/testRunner/unittests/config/commandLineParsing.ts +++ b/src/testRunner/unittests/config/commandLineParsing.ts @@ -57,7 +57,7 @@ namespace ts { assertParseResult(["--lib", "es5,invalidOption", "0.ts"], { errors: [{ - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', '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.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.symbol', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', '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.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.array', 'es2019.symbol', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.", category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, file: undefined, @@ -259,7 +259,7 @@ namespace ts { assertParseResult(["--lib", "es5,", "es7", "0.ts"], { errors: [{ - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', '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.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.symbol', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', '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.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.array', 'es2019.symbol', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.", category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, file: undefined, @@ -278,7 +278,7 @@ namespace ts { assertParseResult(["--lib", "es5, ", "es7", "0.ts"], { errors: [{ - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', '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.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.symbol', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', '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.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.array', 'es2019.symbol', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.", category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, file: undefined, diff --git a/tests/baselines/reference/arrayFlatMap.symbols b/tests/baselines/reference/arrayFlatMap.symbols index 0a97341657b..b3a8d55721a 100644 --- a/tests/baselines/reference/arrayFlatMap.symbols +++ b/tests/baselines/reference/arrayFlatMap.symbols @@ -4,17 +4,17 @@ const array: number[] = []; const readonlyArray: ReadonlyArray = []; >readonlyArray : Symbol(readonlyArray, Decl(arrayFlatMap.ts, 1, 5)) ->ReadonlyArray : Symbol(ReadonlyArray, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2016.array.include.d.ts, --, --), Decl(lib.esnext.array.d.ts, --, --)) +>ReadonlyArray : Symbol(ReadonlyArray, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2016.array.include.d.ts, --, --), Decl(lib.es2019.array.d.ts, --, --)) array.flatMap((): ReadonlyArray => []); // ok ->array.flatMap : Symbol(Array.flatMap, Decl(lib.esnext.array.d.ts, --, --)) +>array.flatMap : Symbol(Array.flatMap, Decl(lib.es2019.array.d.ts, --, --)) >array : Symbol(array, Decl(arrayFlatMap.ts, 0, 5)) ->flatMap : Symbol(Array.flatMap, Decl(lib.esnext.array.d.ts, --, --)) ->ReadonlyArray : Symbol(ReadonlyArray, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2016.array.include.d.ts, --, --), Decl(lib.esnext.array.d.ts, --, --)) +>flatMap : Symbol(Array.flatMap, Decl(lib.es2019.array.d.ts, --, --)) +>ReadonlyArray : Symbol(ReadonlyArray, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2016.array.include.d.ts, --, --), Decl(lib.es2019.array.d.ts, --, --)) readonlyArray.flatMap((): ReadonlyArray => []); // ok ->readonlyArray.flatMap : Symbol(ReadonlyArray.flatMap, Decl(lib.esnext.array.d.ts, --, --)) +>readonlyArray.flatMap : Symbol(ReadonlyArray.flatMap, Decl(lib.es2019.array.d.ts, --, --)) >readonlyArray : Symbol(readonlyArray, Decl(arrayFlatMap.ts, 1, 5)) ->flatMap : Symbol(ReadonlyArray.flatMap, Decl(lib.esnext.array.d.ts, --, --)) ->ReadonlyArray : Symbol(ReadonlyArray, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2016.array.include.d.ts, --, --), Decl(lib.esnext.array.d.ts, --, --)) +>flatMap : Symbol(ReadonlyArray.flatMap, Decl(lib.es2019.array.d.ts, --, --)) +>ReadonlyArray : Symbol(ReadonlyArray, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2016.array.include.d.ts, --, --), Decl(lib.es2019.array.d.ts, --, --)) diff --git a/tests/cases/compiler/arrayFlatMap.ts b/tests/cases/compiler/arrayFlatMap.ts index dc67bf02490..98f84e78773 100644 --- a/tests/cases/compiler/arrayFlatMap.ts +++ b/tests/cases/compiler/arrayFlatMap.ts @@ -1,4 +1,4 @@ -// @lib: esnext +// @lib: es2019 const array: number[] = []; const readonlyArray: ReadonlyArray = []; From b3c179540a3b095d23d67baed57f8779809a34fb Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Fri, 8 Feb 2019 00:51:23 +0900 Subject: [PATCH 027/149] String.prototype.{trimStart,trimEnd} hit stage 4 --- src/compiler/commandLineParser.ts | 1 + src/lib/es2019.d.ts | 1 + src/lib/es2019.string.d.ts | 13 +++++++ src/lib/libs.json | 1 + .../unittests/config/commandLineParsing.ts | 6 ++-- tests/baselines/reference/bigintIndex.symbols | 2 +- tests/baselines/reference/stringTrim.js | 14 ++++++++ tests/baselines/reference/stringTrim.symbols | 24 +++++++++++++ tests/baselines/reference/stringTrim.types | 36 +++++++++++++++++++ tests/cases/compiler/stringTrim.ts | 7 ++++ 10 files changed, 101 insertions(+), 4 deletions(-) create mode 100644 src/lib/es2019.string.d.ts create mode 100644 tests/baselines/reference/stringTrim.js create mode 100644 tests/baselines/reference/stringTrim.symbols create mode 100644 tests/baselines/reference/stringTrim.types create mode 100644 tests/cases/compiler/stringTrim.ts diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index 81884b9c75d..35aeb67df8f 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -43,6 +43,7 @@ namespace ts { ["es2018.promise", "lib.es2018.promise.d.ts"], ["es2018.regexp", "lib.es2018.regexp.d.ts"], ["es2019.array", "lib.es2019.array.d.ts"], + ["es2019.string", "lib.es2019.string.d.ts"], ["es2019.symbol", "lib.es2019.symbol.d.ts"], ["esnext.array", "lib.es2019.array.d.ts"], ["esnext.symbol", "lib.es2019.symbol.d.ts"], diff --git a/src/lib/es2019.d.ts b/src/lib/es2019.d.ts index 217d82a219c..b25f9e1d76a 100644 --- a/src/lib/es2019.d.ts +++ b/src/lib/es2019.d.ts @@ -1,3 +1,4 @@ /// /// +/// /// diff --git a/src/lib/es2019.string.d.ts b/src/lib/es2019.string.d.ts new file mode 100644 index 00000000000..a0cde55c2e5 --- /dev/null +++ b/src/lib/es2019.string.d.ts @@ -0,0 +1,13 @@ +interface String { + /** Removes the trailing white space and line terminator characters from a string. */ + trimEnd(): string; + + /** Removes the leading white space and line terminator characters from a string. */ + trimStart(): string; + + /** Removes the trailing white space and line terminator characters from a string. */ + trimLeft(): string; + + /** Removes the leading white space and line terminator characters from a string. */ + trimRight(): string; +} diff --git a/src/lib/libs.json b/src/lib/libs.json index f1afe448f9f..cb4e6fc053f 100644 --- a/src/lib/libs.json +++ b/src/lib/libs.json @@ -34,6 +34,7 @@ "es2018.promise", "es2018.intl", "es2019.array", + "es2019.string", "es2019.symbol", "esnext.asynciterable", "esnext.bigint", diff --git a/src/testRunner/unittests/config/commandLineParsing.ts b/src/testRunner/unittests/config/commandLineParsing.ts index 387715fe82a..3baf12bd431 100644 --- a/src/testRunner/unittests/config/commandLineParsing.ts +++ b/src/testRunner/unittests/config/commandLineParsing.ts @@ -57,7 +57,7 @@ namespace ts { assertParseResult(["--lib", "es5,invalidOption", "0.ts"], { errors: [{ - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', '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.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.array', 'es2019.symbol', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', '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.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.array', 'es2019.string', 'es2019.symbol', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.", category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, file: undefined, @@ -259,7 +259,7 @@ namespace ts { assertParseResult(["--lib", "es5,", "es7", "0.ts"], { errors: [{ - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', '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.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.array', 'es2019.symbol', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', '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.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.array', 'es2019.string', 'es2019.symbol', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.", category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, file: undefined, @@ -278,7 +278,7 @@ namespace ts { assertParseResult(["--lib", "es5, ", "es7", "0.ts"], { errors: [{ - messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', '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.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.array', 'es2019.symbol', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.", + messageText: "Argument for '--lib' option must be: 'es5', 'es6', 'es2015', 'es7', 'es2016', 'es2017', 'es2018', 'es2019', 'esnext', 'dom', 'dom.iterable', 'webworker', 'webworker.importscripts', '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.string', 'es2017.intl', 'es2017.typedarrays', 'es2018.intl', 'es2018.promise', 'es2018.regexp', 'es2019.array', 'es2019.string', 'es2019.symbol', 'esnext.array', 'esnext.symbol', 'esnext.asynciterable', 'esnext.intl', 'esnext.bigint'.", category: Diagnostics.Argument_for_0_option_must_be_Colon_1.category, code: Diagnostics.Argument_for_0_option_must_be_Colon_1.code, file: undefined, diff --git a/tests/baselines/reference/bigintIndex.symbols b/tests/baselines/reference/bigintIndex.symbols index c0aea092753..dff23a016ee 100644 --- a/tests/baselines/reference/bigintIndex.symbols +++ b/tests/baselines/reference/bigintIndex.symbols @@ -53,7 +53,7 @@ typedArray[bigNum] = 0xAA; // should error typedArray[String(bigNum)] = 0xAA; >typedArray : Symbol(typedArray, Decl(a.ts, 17, 5)) ->String : Symbol(String, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --) ... and 2 more) +>String : Symbol(String, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --) ... and 3 more) >bigNum : Symbol(bigNum, Decl(a.ts, 16, 5)) typedArray["1"] = 0xBB; diff --git a/tests/baselines/reference/stringTrim.js b/tests/baselines/reference/stringTrim.js new file mode 100644 index 00000000000..973df9c1ebb --- /dev/null +++ b/tests/baselines/reference/stringTrim.js @@ -0,0 +1,14 @@ +//// [stringTrim.ts] +var trimmed: string; +trimmed = "abcde".trimEnd(); +trimmed = "abcde".trimStart(); +trimmed = "abcde".trimLeft(); +trimmed = "abcde".trimRight(); + + +//// [stringTrim.js] +var trimmed; +trimmed = "abcde".trimEnd(); +trimmed = "abcde".trimStart(); +trimmed = "abcde".trimLeft(); +trimmed = "abcde".trimRight(); diff --git a/tests/baselines/reference/stringTrim.symbols b/tests/baselines/reference/stringTrim.symbols new file mode 100644 index 00000000000..00f7b34d166 --- /dev/null +++ b/tests/baselines/reference/stringTrim.symbols @@ -0,0 +1,24 @@ +=== tests/cases/compiler/stringTrim.ts === +var trimmed: string; +>trimmed : Symbol(trimmed, Decl(stringTrim.ts, 0, 3)) + +trimmed = "abcde".trimEnd(); +>trimmed : Symbol(trimmed, Decl(stringTrim.ts, 0, 3)) +>"abcde".trimEnd : Symbol(String.trimEnd, Decl(lib.es2019.string.d.ts, --, --)) +>trimEnd : Symbol(String.trimEnd, Decl(lib.es2019.string.d.ts, --, --)) + +trimmed = "abcde".trimStart(); +>trimmed : Symbol(trimmed, Decl(stringTrim.ts, 0, 3)) +>"abcde".trimStart : Symbol(String.trimStart, Decl(lib.es2019.string.d.ts, --, --)) +>trimStart : Symbol(String.trimStart, Decl(lib.es2019.string.d.ts, --, --)) + +trimmed = "abcde".trimLeft(); +>trimmed : Symbol(trimmed, Decl(stringTrim.ts, 0, 3)) +>"abcde".trimLeft : Symbol(String.trimLeft, Decl(lib.es2019.string.d.ts, --, --)) +>trimLeft : Symbol(String.trimLeft, Decl(lib.es2019.string.d.ts, --, --)) + +trimmed = "abcde".trimRight(); +>trimmed : Symbol(trimmed, Decl(stringTrim.ts, 0, 3)) +>"abcde".trimRight : Symbol(String.trimRight, Decl(lib.es2019.string.d.ts, --, --)) +>trimRight : Symbol(String.trimRight, Decl(lib.es2019.string.d.ts, --, --)) + diff --git a/tests/baselines/reference/stringTrim.types b/tests/baselines/reference/stringTrim.types new file mode 100644 index 00000000000..5da0b98fb1a --- /dev/null +++ b/tests/baselines/reference/stringTrim.types @@ -0,0 +1,36 @@ +=== tests/cases/compiler/stringTrim.ts === +var trimmed: string; +>trimmed : string + +trimmed = "abcde".trimEnd(); +>trimmed = "abcde".trimEnd() : string +>trimmed : string +>"abcde".trimEnd() : string +>"abcde".trimEnd : () => string +>"abcde" : "abcde" +>trimEnd : () => string + +trimmed = "abcde".trimStart(); +>trimmed = "abcde".trimStart() : string +>trimmed : string +>"abcde".trimStart() : string +>"abcde".trimStart : () => string +>"abcde" : "abcde" +>trimStart : () => string + +trimmed = "abcde".trimLeft(); +>trimmed = "abcde".trimLeft() : string +>trimmed : string +>"abcde".trimLeft() : string +>"abcde".trimLeft : () => string +>"abcde" : "abcde" +>trimLeft : () => string + +trimmed = "abcde".trimRight(); +>trimmed = "abcde".trimRight() : string +>trimmed : string +>"abcde".trimRight() : string +>"abcde".trimRight : () => string +>"abcde" : "abcde" +>trimRight : () => string + diff --git a/tests/cases/compiler/stringTrim.ts b/tests/cases/compiler/stringTrim.ts new file mode 100644 index 00000000000..d0329b87749 --- /dev/null +++ b/tests/cases/compiler/stringTrim.ts @@ -0,0 +1,7 @@ +// @target: es2019 + +var trimmed: string; +trimmed = "abcde".trimEnd(); +trimmed = "abcde".trimStart(); +trimmed = "abcde".trimLeft(); +trimmed = "abcde".trimRight(); From 343edb6702af5d384cd4fc25d5a8c64d7638f3f6 Mon Sep 17 00:00:00 2001 From: Kagami Sascha Rosylight Date: Fri, 8 Feb 2019 06:59:04 +0900 Subject: [PATCH 028/149] restore lib/* --- lib/lib.esnext.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/lib.esnext.d.ts b/lib/lib.esnext.d.ts index 59d33ab80f4..f213999684d 100644 --- a/lib/lib.esnext.d.ts +++ b/lib/lib.esnext.d.ts @@ -20,6 +20,7 @@ and limitations under the License. /// /// +/// /// /// /// From bc386c11fd3f026ca84ec556b1b8fb4a2eee0038 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Thu, 7 Feb 2019 13:35:07 -0800 Subject: [PATCH 029/149] Use execFileSync in typing installer --- .../unittests/tsserver/typingsInstaller.ts | 12 ++++++------ src/typingsInstaller/nodeTypingsInstaller.ts | 16 ++++++++-------- src/typingsInstallerCore/typingsInstaller.ts | 17 ++++++++++++----- 3 files changed, 26 insertions(+), 19 deletions(-) diff --git a/src/testRunner/unittests/tsserver/typingsInstaller.ts b/src/testRunner/unittests/tsserver/typingsInstaller.ts index 76df9934682..5d648ba23a2 100644 --- a/src/testRunner/unittests/tsserver/typingsInstaller.ts +++ b/src/testRunner/unittests/tsserver/typingsInstaller.ts @@ -1684,9 +1684,9 @@ namespace ts.projectSystem { TI.getNpmCommandForInstallation(npmPath, tsVersion, packageNames, packageNames.length - Math.ceil(packageNames.length / 2)).command ]; it("works when the command is too long to install all packages at once", () => { - const commands: string[] = []; - const hasError = TI.installNpmPackages(npmPath, tsVersion, packageNames, command => { - commands.push(command); + const commands: [string, string[]][] = []; + const hasError = TI.installNpmPackages(npmPath, tsVersion, packageNames, (file, args) => { + commands.push([file, args]); return false; }); assert.isFalse(hasError); @@ -1694,9 +1694,9 @@ namespace ts.projectSystem { }); it("installs remaining packages when one of the partial command fails", () => { - const commands: string[] = []; - const hasError = TI.installNpmPackages(npmPath, tsVersion, packageNames, command => { - commands.push(command); + const commands: [string, string[]][] = []; + const hasError = TI.installNpmPackages(npmPath, tsVersion, packageNames, (file, args) => { + commands.push([file, args]); return commands.length === 1; }); assert.isTrue(hasError); diff --git a/src/typingsInstaller/nodeTypingsInstaller.ts b/src/typingsInstaller/nodeTypingsInstaller.ts index 62bdcfce260..1d75218c883 100644 --- a/src/typingsInstaller/nodeTypingsInstaller.ts +++ b/src/typingsInstaller/nodeTypingsInstaller.ts @@ -70,10 +70,10 @@ namespace ts.server.typingsInstaller { cwd: string; encoding: "utf-8"; } - type ExecSync = (command: string, options: ExecSyncOptions) => string; + type ExecFileSync = (file: string, args: string[], options: ExecSyncOptions) => string; export class NodeTypingsInstaller extends TypingsInstaller { - private readonly nodeExecSync: ExecSync; + private readonly nodeExecFileSync: ExecFileSync; private readonly npmPath: string; readonly typesRegistry: Map>; @@ -97,7 +97,7 @@ namespace ts.server.typingsInstaller { this.log.writeLine(`Process id: ${process.pid}`); this.log.writeLine(`NPM location: ${this.npmPath} (explicit '${Arguments.NpmLocation}' ${npmLocation === undefined ? "not " : ""} provided)`); } - ({ execSync: this.nodeExecSync } = require("child_process")); + ({ execFileSync: this.nodeExecFileSync } = require("child_process")); this.ensurePackageDirectoryExists(globalTypingsCacheLocation); @@ -105,7 +105,7 @@ namespace ts.server.typingsInstaller { if (this.log.isEnabled()) { this.log.writeLine(`Updating ${typesRegistryPackageName} npm package...`); } - this.execSyncAndLog(`${this.npmPath} install --ignore-scripts ${typesRegistryPackageName}@${this.latestDistTag}`, { cwd: globalTypingsCacheLocation }); + this.execFileSyncAndLog(this.npmPath, ["install", "--ignore-scripts", `${typesRegistryPackageName}@${this.latestDistTag}`], { cwd: globalTypingsCacheLocation }); if (this.log.isEnabled()) { this.log.writeLine(`Updated ${typesRegistryPackageName} npm package`); } @@ -189,7 +189,7 @@ namespace ts.server.typingsInstaller { this.log.writeLine(`#${requestId} with arguments'${JSON.stringify(packageNames)}'.`); } const start = Date.now(); - const hasError = installNpmPackages(this.npmPath, version, packageNames, command => this.execSyncAndLog(command, { cwd })); + const hasError = installNpmPackages(this.npmPath, version, packageNames, (file, args) => this.execFileSyncAndLog(file, args, { cwd })); if (this.log.isEnabled()) { this.log.writeLine(`npm install #${requestId} took: ${Date.now() - start} ms`); } @@ -197,12 +197,12 @@ namespace ts.server.typingsInstaller { } /** Returns 'true' in case of error. */ - private execSyncAndLog(command: string, options: Pick): boolean { + private execFileSyncAndLog(file: string, args: string[], options: Pick): boolean { if (this.log.isEnabled()) { - this.log.writeLine(`Exec: ${command}`); + this.log.writeLine(`Exec: ${file} ${args.join(" ")}`); } try { - const stdout = this.nodeExecSync(command, { ...options, encoding: "utf-8" }); + const stdout = this.nodeExecFileSync(file, args, { ...options, encoding: "utf-8" }); if (this.log.isEnabled()) { this.log.writeLine(` Succeeded. stdout:${indent(sys.newLine, stdout)}`); } diff --git a/src/typingsInstallerCore/typingsInstaller.ts b/src/typingsInstallerCore/typingsInstaller.ts index df83f1a677c..3d0858d7dfe 100644 --- a/src/typingsInstallerCore/typingsInstaller.ts +++ b/src/typingsInstallerCore/typingsInstaller.ts @@ -31,28 +31,35 @@ namespace ts.server.typingsInstaller { } /*@internal*/ - export function installNpmPackages(npmPath: string, tsVersion: string, packageNames: string[], install: (command: string) => boolean) { + export function installNpmPackages(npmPath: string, tsVersion: string, packageNames: string[], install: (file: string, args: string[]) => boolean) { let hasError = false; for (let remaining = packageNames.length; remaining > 0;) { const result = getNpmCommandForInstallation(npmPath, tsVersion, packageNames, remaining); remaining = result.remaining; - hasError = install(result.command) || hasError; + hasError = install(result.command[0], result.command[1]) || hasError; } return hasError; } + function getUserAgent(tsVersion: string) { + return `--user-agent="typesInstaller/${tsVersion}"`; + } + const npmInstall = "install", ignoreScripts = "--ignore-scripts", saveDev = "--save-dev"; + const commandBaseLength = npmInstall.length + ignoreScripts.length + saveDev.length + getUserAgent("").length + 5; /*@internal*/ export function getNpmCommandForInstallation(npmPath: string, tsVersion: string, packageNames: string[], remaining: number) { const sliceStart = packageNames.length - remaining; - let command: string, toSlice = remaining; + let packages: string[], toSlice = remaining; while (true) { - command = `${npmPath} install --ignore-scripts ${(toSlice === packageNames.length ? packageNames : packageNames.slice(sliceStart, sliceStart + toSlice)).join(" ")} --save-dev --user-agent="typesInstaller/${tsVersion}"`; - if (command.length < 8000) { + packages = toSlice === packageNames.length ? packageNames : packageNames.slice(sliceStart, sliceStart + toSlice); + const commandLength = npmPath.length + commandBaseLength + packages.join(" ").length + tsVersion.length; + if (commandLength < 8000) { break; } toSlice = toSlice - Math.floor(toSlice / 2); } + const command: [string, string[]] = [npmPath, [npmInstall, ignoreScripts, ...packages, saveDev, getUserAgent(tsVersion)]]; return { command, remaining: remaining - toSlice }; } From f46c0a45979669daf2067c3990bf604a7d35dcaf Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Fri, 8 Feb 2019 06:49:13 -0800 Subject: [PATCH 030/149] Process more complex constraints as per CR feedback --- src/compiler/checker.ts | 39 +++++++++++++++++++-------------------- 1 file changed, 19 insertions(+), 20 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index aa5007065fc..bdb645a0003 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -14570,19 +14570,8 @@ namespace ts { return undefined; } - function inferToHomomorphicMappedType(source: Type, target: MappedType, constraintType: IndexType) { - const inference = getInferenceInfoForType(constraintType.type); - if (inference && !inference.isFixed) { - const inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType); - if (inferredType) { - const savePriority = priority; - priority |= InferencePriority.HomomorphicMappedType; - inferFromTypes(inferredType, inference.typeParameter); - priority = savePriority; - } - } - } - + // target: { [P in 'a' | 'b' | keyof T | keyof U]: XXX } + // source: { a: xxx, b: xxx, c: xxx, d: xxx } function inferToMappedType(source: Type, target: MappedType, constraintType: Type): boolean { if (constraintType.flags & TypeFlags.Union) { let result = false; @@ -14596,7 +14585,16 @@ namespace ts { // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source // type and then make a secondary inference from that type to T. We make a secondary inference // such that direct inferences to T get priority over inferences to Partial, for example. - inferToHomomorphicMappedType(source, target, constraintType); + const inference = getInferenceInfoForType((constraintType).type); + if (inference && !inference.isFixed) { + const inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType); + if (inferredType) { + const savePriority = priority; + priority |= InferencePriority.HomomorphicMappedType; + inferFromTypes(inferredType, inference.typeParameter); + priority = savePriority; + } + } return true; } if (constraintType.flags & TypeFlags.TypeParameter) { @@ -14606,15 +14604,16 @@ namespace ts { priority |= InferencePriority.MappedTypeConstraint; inferFromTypes(getIndexType(source), constraintType); priority = savePriority; - // If K is constrained to an index type keyof T, where T is a type parameter, proceed to make - // the same inferences as we would for a homomorphic mapped type { [P in keyof T]: X } (this - // enables us to make meaningful inferences when the target is a Pick). Otherwise, infer - // from a union of the property types in the source to the template type X. + // If K is constrained to a type C, also infer to C. Thus, for a mapped type { [P in K]: X }, + // where K extends keyof T, we make the same inferences as for a homomorphic mapped type + // { [P in keyof T]: X }. This enables us to make meaningful inferences when the target is a + // Pick. const extendedConstraint = getConstraintOfType(constraintType); - if (extendedConstraint && extendedConstraint.flags & TypeFlags.Index) { - inferToHomomorphicMappedType(source, target, extendedConstraint); + if (extendedConstraint && inferToMappedType(source, target, extendedConstraint)) { return true; } + // If no inferences can be made to K's constraint, infer from a union of the property types + // in the source to the template type X. const valueTypes = compact([ getIndexTypeOfType(source, IndexKind.String), getIndexTypeOfType(source, IndexKind.Number), From e49320d1db82ae4e281914ab3b6c4d101da4e16d Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Fri, 8 Feb 2019 06:49:26 -0800 Subject: [PATCH 031/149] Add more tests --- .../conformance/types/mapped/isomorphicMappedTypeInference.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/cases/conformance/types/mapped/isomorphicMappedTypeInference.ts b/tests/cases/conformance/types/mapped/isomorphicMappedTypeInference.ts index 534d50c367e..031cf840d33 100644 --- a/tests/cases/conformance/types/mapped/isomorphicMappedTypeInference.ts +++ b/tests/cases/conformance/types/mapped/isomorphicMappedTypeInference.ts @@ -160,10 +160,14 @@ o = foo(o, {b: 9}); declare function f20(obj: Pick): T; declare function f21(obj: Pick): K; declare function f22(obj: Boxified>): T; +declare function f23(obj: Pick): T; +declare function f24(obj: Pick): T & U; let x0 = f20({ foo: 42, bar: "hello" }); let x1 = f21({ foo: 42, bar: "hello" }); let x2 = f22({ foo: { value: 42} , bar: { value: "hello" } }); +let x3 = f23({ foo: 42, bar: "hello" }); +let x4 = f24({ foo: 42, bar: "hello" }); // Repro from #29765 From 8652158ead4af506a604d70ad80becba7ddccea9 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Fri, 8 Feb 2019 06:49:33 -0800 Subject: [PATCH 032/149] Accept new baselines --- .../isomorphicMappedTypeInference.js | 19 ++++ .../isomorphicMappedTypeInference.symbols | 100 ++++++++++++------ .../isomorphicMappedTypeInference.types | 28 +++++ 3 files changed, 117 insertions(+), 30 deletions(-) diff --git a/tests/baselines/reference/isomorphicMappedTypeInference.js b/tests/baselines/reference/isomorphicMappedTypeInference.js index 6cfc2ec7350..aa904e9afa1 100644 --- a/tests/baselines/reference/isomorphicMappedTypeInference.js +++ b/tests/baselines/reference/isomorphicMappedTypeInference.js @@ -157,10 +157,14 @@ o = foo(o, {b: 9}); declare function f20(obj: Pick): T; declare function f21(obj: Pick): K; declare function f22(obj: Boxified>): T; +declare function f23(obj: Pick): T; +declare function f24(obj: Pick): T & U; let x0 = f20({ foo: 42, bar: "hello" }); let x1 = f21({ foo: 42, bar: "hello" }); let x2 = f22({ foo: { value: 42} , bar: { value: "hello" } }); +let x3 = f23({ foo: 42, bar: "hello" }); +let x4 = f24({ foo: 42, bar: "hello" }); // Repro from #29765 @@ -282,6 +286,8 @@ o = foo(o, { b: 9 }); var x0 = f20({ foo: 42, bar: "hello" }); var x1 = f21({ foo: 42, bar: "hello" }); var x2 = f22({ foo: { value: 42 }, bar: { value: "hello" } }); +var x3 = f23({ foo: 42, bar: "hello" }); +var x4 = f24({ foo: 42, bar: "hello" }); // Repro from #29765 function getProps(obj, list) { return {}; @@ -360,6 +366,8 @@ declare let o: { declare function f20(obj: Pick): T; declare function f21(obj: Pick): K; declare function f22(obj: Boxified>): T; +declare function f23(obj: Pick): T; +declare function f24(obj: Pick): T & U; declare let x0: { foo: number; bar: string; @@ -369,6 +377,17 @@ declare let x2: { foo: number; bar: string; }; +declare let x3: { + foo: number; + bar: string; +}; +declare let x4: { + foo: number; + bar: string; +} & { + foo: number; + bar: string; +}; declare function getProps(obj: T, list: K[]): Pick; declare const myAny: any; declare const o1: Pick; diff --git a/tests/baselines/reference/isomorphicMappedTypeInference.symbols b/tests/baselines/reference/isomorphicMappedTypeInference.symbols index 6f999f91dc4..3192be13ff6 100644 --- a/tests/baselines/reference/isomorphicMappedTypeInference.symbols +++ b/tests/baselines/reference/isomorphicMappedTypeInference.symbols @@ -523,56 +523,96 @@ declare function f22(obj: Boxified>): T; >K : Symbol(K, Decl(isomorphicMappedTypeInference.ts, 157, 23)) >T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 157, 21)) +declare function f23(obj: Pick): T; +>f23 : Symbol(f23, Decl(isomorphicMappedTypeInference.ts, 157, 73)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 158, 21)) +>U : Symbol(U, Decl(isomorphicMappedTypeInference.ts, 158, 23)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 158, 21)) +>K : Symbol(K, Decl(isomorphicMappedTypeInference.ts, 158, 42)) +>U : Symbol(U, Decl(isomorphicMappedTypeInference.ts, 158, 23)) +>obj : Symbol(obj, Decl(isomorphicMappedTypeInference.ts, 158, 56)) +>Pick : Symbol(Pick, Decl(lib.es5.d.ts, --, --)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 158, 21)) +>K : Symbol(K, Decl(isomorphicMappedTypeInference.ts, 158, 42)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 158, 21)) + +declare function f24(obj: Pick): T & U; +>f24 : Symbol(f24, Decl(isomorphicMappedTypeInference.ts, 158, 76)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 159, 21)) +>U : Symbol(U, Decl(isomorphicMappedTypeInference.ts, 159, 23)) +>K : Symbol(K, Decl(isomorphicMappedTypeInference.ts, 159, 26)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 159, 21)) +>U : Symbol(U, Decl(isomorphicMappedTypeInference.ts, 159, 23)) +>obj : Symbol(obj, Decl(isomorphicMappedTypeInference.ts, 159, 56)) +>Pick : Symbol(Pick, Decl(lib.es5.d.ts, --, --)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 159, 21)) +>U : Symbol(U, Decl(isomorphicMappedTypeInference.ts, 159, 23)) +>K : Symbol(K, Decl(isomorphicMappedTypeInference.ts, 159, 26)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 159, 21)) +>U : Symbol(U, Decl(isomorphicMappedTypeInference.ts, 159, 23)) + let x0 = f20({ foo: 42, bar: "hello" }); ->x0 : Symbol(x0, Decl(isomorphicMappedTypeInference.ts, 159, 3)) +>x0 : Symbol(x0, Decl(isomorphicMappedTypeInference.ts, 161, 3)) >f20 : Symbol(f20, Decl(isomorphicMappedTypeInference.ts, 150, 19)) ->foo : Symbol(foo, Decl(isomorphicMappedTypeInference.ts, 159, 14)) ->bar : Symbol(bar, Decl(isomorphicMappedTypeInference.ts, 159, 23)) +>foo : Symbol(foo, Decl(isomorphicMappedTypeInference.ts, 161, 14)) +>bar : Symbol(bar, Decl(isomorphicMappedTypeInference.ts, 161, 23)) let x1 = f21({ foo: 42, bar: "hello" }); ->x1 : Symbol(x1, Decl(isomorphicMappedTypeInference.ts, 160, 3)) +>x1 : Symbol(x1, Decl(isomorphicMappedTypeInference.ts, 162, 3)) >f21 : Symbol(f21, Decl(isomorphicMappedTypeInference.ts, 155, 63)) ->foo : Symbol(foo, Decl(isomorphicMappedTypeInference.ts, 160, 14)) ->bar : Symbol(bar, Decl(isomorphicMappedTypeInference.ts, 160, 23)) +>foo : Symbol(foo, Decl(isomorphicMappedTypeInference.ts, 162, 14)) +>bar : Symbol(bar, Decl(isomorphicMappedTypeInference.ts, 162, 23)) let x2 = f22({ foo: { value: 42} , bar: { value: "hello" } }); ->x2 : Symbol(x2, Decl(isomorphicMappedTypeInference.ts, 161, 3)) +>x2 : Symbol(x2, Decl(isomorphicMappedTypeInference.ts, 163, 3)) >f22 : Symbol(f22, Decl(isomorphicMappedTypeInference.ts, 156, 63)) ->foo : Symbol(foo, Decl(isomorphicMappedTypeInference.ts, 161, 14)) ->value : Symbol(value, Decl(isomorphicMappedTypeInference.ts, 161, 21)) ->bar : Symbol(bar, Decl(isomorphicMappedTypeInference.ts, 161, 34)) ->value : Symbol(value, Decl(isomorphicMappedTypeInference.ts, 161, 41)) +>foo : Symbol(foo, Decl(isomorphicMappedTypeInference.ts, 163, 14)) +>value : Symbol(value, Decl(isomorphicMappedTypeInference.ts, 163, 21)) +>bar : Symbol(bar, Decl(isomorphicMappedTypeInference.ts, 163, 34)) +>value : Symbol(value, Decl(isomorphicMappedTypeInference.ts, 163, 41)) + +let x3 = f23({ foo: 42, bar: "hello" }); +>x3 : Symbol(x3, Decl(isomorphicMappedTypeInference.ts, 164, 3)) +>f23 : Symbol(f23, Decl(isomorphicMappedTypeInference.ts, 157, 73)) +>foo : Symbol(foo, Decl(isomorphicMappedTypeInference.ts, 164, 14)) +>bar : Symbol(bar, Decl(isomorphicMappedTypeInference.ts, 164, 23)) + +let x4 = f24({ foo: 42, bar: "hello" }); +>x4 : Symbol(x4, Decl(isomorphicMappedTypeInference.ts, 165, 3)) +>f24 : Symbol(f24, Decl(isomorphicMappedTypeInference.ts, 158, 76)) +>foo : Symbol(foo, Decl(isomorphicMappedTypeInference.ts, 165, 14)) +>bar : Symbol(bar, Decl(isomorphicMappedTypeInference.ts, 165, 23)) // Repro from #29765 function getProps(obj: T, list: K[]): Pick { ->getProps : Symbol(getProps, Decl(isomorphicMappedTypeInference.ts, 161, 62)) ->T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 165, 18)) ->K : Symbol(K, Decl(isomorphicMappedTypeInference.ts, 165, 20)) ->T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 165, 18)) ->obj : Symbol(obj, Decl(isomorphicMappedTypeInference.ts, 165, 40)) ->T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 165, 18)) ->list : Symbol(list, Decl(isomorphicMappedTypeInference.ts, 165, 47)) ->K : Symbol(K, Decl(isomorphicMappedTypeInference.ts, 165, 20)) +>getProps : Symbol(getProps, Decl(isomorphicMappedTypeInference.ts, 165, 40)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 169, 18)) +>K : Symbol(K, Decl(isomorphicMappedTypeInference.ts, 169, 20)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 169, 18)) +>obj : Symbol(obj, Decl(isomorphicMappedTypeInference.ts, 169, 40)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 169, 18)) +>list : Symbol(list, Decl(isomorphicMappedTypeInference.ts, 169, 47)) +>K : Symbol(K, Decl(isomorphicMappedTypeInference.ts, 169, 20)) >Pick : Symbol(Pick, Decl(lib.es5.d.ts, --, --)) ->T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 165, 18)) ->K : Symbol(K, Decl(isomorphicMappedTypeInference.ts, 165, 20)) +>T : Symbol(T, Decl(isomorphicMappedTypeInference.ts, 169, 18)) +>K : Symbol(K, Decl(isomorphicMappedTypeInference.ts, 169, 20)) return {} as any; } const myAny: any = {}; ->myAny : Symbol(myAny, Decl(isomorphicMappedTypeInference.ts, 169, 5)) +>myAny : Symbol(myAny, Decl(isomorphicMappedTypeInference.ts, 173, 5)) const o1 = getProps(myAny, ['foo', 'bar']); ->o1 : Symbol(o1, Decl(isomorphicMappedTypeInference.ts, 171, 5)) ->getProps : Symbol(getProps, Decl(isomorphicMappedTypeInference.ts, 161, 62)) ->myAny : Symbol(myAny, Decl(isomorphicMappedTypeInference.ts, 169, 5)) +>o1 : Symbol(o1, Decl(isomorphicMappedTypeInference.ts, 175, 5)) +>getProps : Symbol(getProps, Decl(isomorphicMappedTypeInference.ts, 165, 40)) +>myAny : Symbol(myAny, Decl(isomorphicMappedTypeInference.ts, 173, 5)) const o2: { foo: any; bar: any } = getProps(myAny, ['foo', 'bar']); ->o2 : Symbol(o2, Decl(isomorphicMappedTypeInference.ts, 173, 5)) ->foo : Symbol(foo, Decl(isomorphicMappedTypeInference.ts, 173, 11)) ->bar : Symbol(bar, Decl(isomorphicMappedTypeInference.ts, 173, 21)) ->getProps : Symbol(getProps, Decl(isomorphicMappedTypeInference.ts, 161, 62)) ->myAny : Symbol(myAny, Decl(isomorphicMappedTypeInference.ts, 169, 5)) +>o2 : Symbol(o2, Decl(isomorphicMappedTypeInference.ts, 177, 5)) +>foo : Symbol(foo, Decl(isomorphicMappedTypeInference.ts, 177, 11)) +>bar : Symbol(bar, Decl(isomorphicMappedTypeInference.ts, 177, 21)) +>getProps : Symbol(getProps, Decl(isomorphicMappedTypeInference.ts, 165, 40)) +>myAny : Symbol(myAny, Decl(isomorphicMappedTypeInference.ts, 173, 5)) diff --git a/tests/baselines/reference/isomorphicMappedTypeInference.types b/tests/baselines/reference/isomorphicMappedTypeInference.types index b37175b5eed..1f1fa0d200a 100644 --- a/tests/baselines/reference/isomorphicMappedTypeInference.types +++ b/tests/baselines/reference/isomorphicMappedTypeInference.types @@ -522,6 +522,14 @@ declare function f22(obj: Boxified>): T; >f22 : (obj: Boxified>) => T >obj : Boxified> +declare function f23(obj: Pick): T; +>f23 : (obj: Pick) => T +>obj : Pick + +declare function f24(obj: Pick): T & U; +>f24 : (obj: Pick) => T & U +>obj : Pick + let x0 = f20({ foo: 42, bar: "hello" }); >x0 : { foo: number; bar: string; } >f20({ foo: 42, bar: "hello" }) : { foo: number; bar: string; } @@ -556,6 +564,26 @@ let x2 = f22({ foo: { value: 42} , bar: { value: "hello" } }); >value : string >"hello" : "hello" +let x3 = f23({ foo: 42, bar: "hello" }); +>x3 : { foo: number; bar: string; } +>f23({ foo: 42, bar: "hello" }) : { foo: number; bar: string; } +>f23 : (obj: Pick) => T +>{ foo: 42, bar: "hello" } : { foo: number; bar: string; } +>foo : number +>42 : 42 +>bar : string +>"hello" : "hello" + +let x4 = f24({ foo: 42, bar: "hello" }); +>x4 : { foo: number; bar: string; } & { foo: number; bar: string; } +>f24({ foo: 42, bar: "hello" }) : { foo: number; bar: string; } & { foo: number; bar: string; } +>f24 : (obj: Pick) => T & U +>{ foo: 42, bar: "hello" } : { foo: number; bar: string; } +>foo : number +>42 : 42 +>bar : string +>"hello" : "hello" + // Repro from #29765 function getProps(obj: T, list: K[]): Pick { From 040401205ba51d036b9ec234ff2f2341ceac96b9 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Fri, 8 Feb 2019 06:53:39 -0800 Subject: [PATCH 033/149] Delete wayward comment --- src/compiler/checker.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index bdb645a0003..b550710861c 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -14570,8 +14570,6 @@ namespace ts { return undefined; } - // target: { [P in 'a' | 'b' | keyof T | keyof U]: XXX } - // source: { a: xxx, b: xxx, c: xxx, d: xxx } function inferToMappedType(source: Type, target: MappedType, constraintType: Type): boolean { if (constraintType.flags & TypeFlags.Union) { let result = false; From 61a05018cba05d223aee07432a697fe316d5ed36 Mon Sep 17 00:00:00 2001 From: TypeScript Bot Date: Fri, 8 Feb 2019 10:49:28 -0800 Subject: [PATCH 034/149] Update user baselines (#29800) --- .../user/chrome-devtools-frontend.log | 274 +++++++++++++++--- tests/baselines/reference/user/npm.log | 4 +- 2 files changed, 232 insertions(+), 46 deletions(-) diff --git a/tests/baselines/reference/user/chrome-devtools-frontend.log b/tests/baselines/reference/user/chrome-devtools-frontend.log index 7ae2531d383..3c86f06756a 100644 --- a/tests/baselines/reference/user/chrome-devtools-frontend.log +++ b/tests/baselines/reference/user/chrome-devtools-frontend.log @@ -1,16 +1,16 @@ Exit Code: 1 Standard output: -../../../../built/local/lib.dom.d.ts(2388,11): error TS2300: Duplicate identifier 'CSSRule'. -../../../../built/local/lib.dom.d.ts(2407,13): error TS2300: Duplicate identifier 'CSSRule'. -../../../../built/local/lib.dom.d.ts(3267,11): error TS2300: Duplicate identifier 'Comment'. -../../../../built/local/lib.dom.d.ts(3270,13): error TS2300: Duplicate identifier 'Comment'. -../../../../built/local/lib.dom.d.ts(4963,11): error TS2300: Duplicate identifier 'Event'. -../../../../built/local/lib.dom.d.ts(5023,13): error TS2300: Duplicate identifier 'Event'. -../../../../built/local/lib.dom.d.ts(11214,11): error TS2300: Duplicate identifier 'Position'. -../../../../built/local/lib.dom.d.ts(11959,11): error TS2300: Duplicate identifier 'Request'. -../../../../built/local/lib.dom.d.ts(12039,13): error TS2300: Duplicate identifier 'Request'. -../../../../built/local/lib.dom.d.ts(16513,11): error TS2300: Duplicate identifier 'Window'. -../../../../built/local/lib.dom.d.ts(16644,13): error TS2300: Duplicate identifier 'Window'. +../../../../built/local/lib.dom.d.ts(2439,11): error TS2300: Duplicate identifier 'CSSRule'. +../../../../built/local/lib.dom.d.ts(2458,13): error TS2300: Duplicate identifier 'CSSRule'. +../../../../built/local/lib.dom.d.ts(3339,11): error TS2300: Duplicate identifier 'Comment'. +../../../../built/local/lib.dom.d.ts(3342,13): error TS2300: Duplicate identifier 'Comment'. +../../../../built/local/lib.dom.d.ts(5032,11): error TS2300: Duplicate identifier 'Event'. +../../../../built/local/lib.dom.d.ts(5092,13): error TS2300: Duplicate identifier 'Event'. +../../../../built/local/lib.dom.d.ts(11453,11): error TS2300: Duplicate identifier 'Position'. +../../../../built/local/lib.dom.d.ts(12214,11): error TS2300: Duplicate identifier 'Request'. +../../../../built/local/lib.dom.d.ts(12294,13): error TS2300: Duplicate identifier 'Request'. +../../../../built/local/lib.dom.d.ts(16941,11): error TS2300: Duplicate identifier 'Window'. +../../../../built/local/lib.dom.d.ts(17073,13): error TS2300: Duplicate identifier 'Window'. ../../../../built/local/lib.es5.d.ts(1416,11): error TS2300: Duplicate identifier 'ArrayLike'. ../../../../built/local/lib.es5.d.ts(1452,6): error TS2300: Duplicate identifier 'Record'. ../../../../node_modules/@types/node/index.d.ts(150,13): error TS2403: Subsequent variable declarations must have the same type. Variable 'module' must be of type '{}', but here has type 'NodeModule'. @@ -158,7 +158,7 @@ node_modules/chrome-devtools-frontend/front_end/accessibility/AXBreadcrumbsPane. node_modules/chrome-devtools-frontend/front_end/accessibility/AXBreadcrumbsPane.js(391,50): error TS2345: Argument of type '0' is not assignable to parameter of type 'string'. node_modules/chrome-devtools-frontend/front_end/accessibility/AXBreadcrumbsPane.js(393,50): error TS2345: Argument of type '-1' is not assignable to parameter of type 'string'. node_modules/chrome-devtools-frontend/front_end/accessibility/AXBreadcrumbsPane.js(396,27): error TS2339: Property 'focus' does not exist on type 'Element'. -node_modules/chrome-devtools-frontend/front_end/accessibility/AXBreadcrumbsPane.js(447,26): error TS2339: Property 'breadcrumb' does not exist on type 'Node'. +node_modules/chrome-devtools-frontend/front_end/accessibility/AXBreadcrumbsPane.js(447,26): error TS2339: Property 'breadcrumb' does not exist on type 'ChildNode'. node_modules/chrome-devtools-frontend/front_end/accessibility/AXBreadcrumbsPane.js(457,30): error TS2339: Property 'breadcrumb' does not exist on type 'Node'. node_modules/chrome-devtools-frontend/front_end/accessibility/AXBreadcrumbsPane.js(473,24): error TS2694: Namespace 'Protocol' has no exported member 'Accessibility'. node_modules/chrome-devtools-frontend/front_end/accessibility/AXBreadcrumbsPane.js(481,17): error TS2339: Property 'setTextContentTruncatedIfNeeded' does not exist on type 'Element'. @@ -699,10 +699,6 @@ node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighth node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(9093,1): error TS2554: Expected 0-2 arguments, but got 3. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(9117,1): error TS2554: Expected 0-2 arguments, but got 3. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(9467,15): error TS2339: Property 'axe' does not exist on type 'Window'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(9708,34): error TS2345: Argument of type 'any[][]' is not assignable to parameter of type 'readonly [any, any][]'. - Type 'any[]' is missing the following properties from type '[any, any]': 0, 1 -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(9948,10): error TS2693: 'ShadowRoot' only refers to a type, but is being used as a value here. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(9969,4): error TS2693: 'ShadowRoot' only refers to a type, but is being used as a value here. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(10092,16): error TS2304: Cannot find name 'd41d8cd98f00b204e9800998ecf8427e_LibraryDetectorTests'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(10513,19): error TS2488: Type 'NodeListOf' must have a '[Symbol.iterator]()' method that returns an iterator. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(10811,19): error TS2304: Cannot find name 'getElementsInDocument'. @@ -3981,7 +3977,7 @@ node_modules/chrome-devtools-frontend/front_end/console/ConsoleSidebar.js(107,9) node_modules/chrome-devtools-frontend/front_end/console/ConsoleSidebar.js(111,9): error TS2339: Property 'ConsoleSidebar' does not exist on type '{ new (): Console; prototype: Console; }'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleSidebar.js(119,47): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleSidebar.js(122,25): error TS2345: Argument of type 'Element' is not assignable to parameter of type 'Icon'. - Type 'Element' is missing the following properties from type 'Icon': createdCallback, _descriptor, _spriteSheet, _iconType, and 116 more. + Type 'Element' is missing the following properties from type 'Icon': createdCallback, _descriptor, _spriteSheet, _iconType, and 117 more. node_modules/chrome-devtools-frontend/front_end/console/ConsoleSidebar.js(133,9): error TS2339: Property 'ConsoleSidebar' does not exist on type '{ new (): Console; prototype: Console; }'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleSidebar.js(147,27): error TS2322: Type 'Element' is not assignable to type 'Icon'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleSidebar.js(177,60): error TS2555: Expected at least 2 arguments, but got 1. @@ -5065,8 +5061,6 @@ node_modules/chrome-devtools-frontend/front_end/dom_extension/DOMExtension.js(25 node_modules/chrome-devtools-frontend/front_end/dom_extension/DOMExtension.js(253,61): error TS2339: Property 'host' does not exist on type 'Node'. node_modules/chrome-devtools-frontend/front_end/dom_extension/DOMExtension.js(254,17): error TS2339: Property 'host' does not exist on type 'Node'. node_modules/chrome-devtools-frontend/front_end/dom_extension/DOMExtension.js(261,16): error TS2339: Property 'getComponentSelection' does not exist on type 'Node'. -node_modules/chrome-devtools-frontend/front_end/dom_extension/DOMExtension.js(265,28): error TS2693: 'ShadowRoot' only refers to a type, but is being used as a value here. -node_modules/chrome-devtools-frontend/front_end/dom_extension/DOMExtension.js(265,48): error TS2339: Property 'getSelection' does not exist on type 'Node & ParentNode'. node_modules/chrome-devtools-frontend/front_end/dom_extension/DOMExtension.js(265,70): error TS2339: Property 'window' does not exist on type 'Node'. node_modules/chrome-devtools-frontend/front_end/dom_extension/DOMExtension.js(271,16): error TS2339: Property 'hasSelection' does not exist on type 'Node'. node_modules/chrome-devtools-frontend/front_end/dom_extension/DOMExtension.js(273,23): error TS2339: Property 'querySelectorAll' does not exist on type 'Node'. @@ -5149,7 +5143,7 @@ node_modules/chrome-devtools-frontend/front_end/dom_extension/DOMExtension.js(74 node_modules/chrome-devtools-frontend/front_end/dom_extension/DOMExtension.js(745,48): error TS2339: Property 'pageX' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/dom_extension/DOMExtension.js(745,60): error TS2339: Property 'pageY' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/dom_extension/DOMExtension.js(753,20): error TS2339: Property 'deepElementFromPoint' does not exist on type 'Document'. -node_modules/chrome-devtools-frontend/front_end/dom_extension/DOMExtension.js(761,5): error TS2740: Type 'ShadowRoot' is missing the following properties from type 'Document': URL, alinkColor, all, anchors, and 169 more. +node_modules/chrome-devtools-frontend/front_end/dom_extension/DOMExtension.js(761,5): error TS2740: Type 'ShadowRoot' is missing the following properties from type 'Document': URL, alinkColor, all, anchors, and 174 more. node_modules/chrome-devtools-frontend/front_end/dom_extension/DOMExtension.js(766,28): error TS2339: Property 'deepElementFromPoint' does not exist on type 'DocumentFragment'. node_modules/chrome-devtools-frontend/front_end/dom_extension/DOMExtension.js(766,70): error TS2339: Property 'deepElementFromPoint' does not exist on type 'Document'. node_modules/chrome-devtools-frontend/front_end/dom_extension/DOMExtension.js(771,20): error TS2339: Property 'deepActiveElement' does not exist on type 'Document'. @@ -5367,7 +5361,7 @@ node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js( node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(575,10): error TS2339: Property 'style' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(576,10): error TS2339: Property 'style' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(580,10): error TS2339: Property 'scrollIntoViewIfNeeded' does not exist on type 'Element'. -node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(592,20): error TS2339: Property 'classList' does not exist on type 'Node'. +node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(592,20): error TS2339: Property 'classList' does not exist on type 'ChildNode'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(600,41): error TS2339: Property 'isAncestor' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(632,27): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(655,26): error TS2339: Property 'getComponentSelection' does not exist on type 'Element'. @@ -5377,7 +5371,6 @@ node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js( node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(738,14): error TS7014: Function type, which lacks return-type annotation, implicitly has an 'any' return type. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(739,14): error TS7014: Function type, which lacks return-type annotation, implicitly has an 'any' return type. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(762,13): error TS2339: Property 'style' does not exist on type 'ChildNode'. -node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(763,7): error TS2739: Type 'Node' is missing the following properties from type 'ChildNode': after, before, remove, replaceWith node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(767,32): error TS2339: Property 'style' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(772,10): error TS2339: Property 'runtime' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(796,24): error TS2339: Property 'setMultilineEditing' does not exist on type 'TreeOutline'. @@ -5385,7 +5378,6 @@ node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js( node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(803,60): error TS2339: Property 'visibleWidth' does not exist on type 'TreeOutline'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(828,34): error TS2339: Property 'style' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(832,15): error TS2339: Property 'style' does not exist on type 'ChildNode'. -node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(833,9): error TS2322: Type 'Node' is not assignable to type 'ChildNode'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(837,26): error TS2339: Property 'setMultilineEditing' does not exist on type 'TreeOutline'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(851,18): error TS2339: Property 'altKey' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeElement.js(851,35): error TS2339: Property 'shiftKey' does not exist on type 'Event'. @@ -5466,7 +5458,7 @@ node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js( node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(755,33): error TS2339: Property 'enclosingNodeOrSelfWithClass' does not exist on type 'EventTarget'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(758,36): error TS2339: Property 'enclosingNodeOrSelfWithClass' does not exist on type 'EventTarget'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(813,22): error TS2339: Property 'index' does not exist on type 'DOMNode'. -node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(920,9): error TS2740: Type 'Node & ParentNode' is missing the following properties from type 'Element': assignedSlot, attributes, classList, className, and 63 more. +node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(920,9): error TS2740: Type 'Node & ParentNode' is missing the following properties from type 'Element': assignedSlot, attributes, classList, className, and 64 more. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(930,13): error TS2339: Property 'type' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(1010,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/elements/ElementsTreeOutline.js(1025,22): error TS2694: Namespace 'Common' has no exported member 'Event'. @@ -5658,14 +5650,13 @@ node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(10 node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(1040,69): error TS2339: Property 'selectorText' does not exist on type 'CSSRule'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(1055,24): error TS2339: Property '_section' does not exist on type 'ChildNode'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(1056,29): error TS2339: Property '_section' does not exist on type 'ChildNode'. -node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(1057,7): error TS2322: Type 'Node' is not assignable to type 'ChildNode'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(1073,24): error TS2339: Property '_section' does not exist on type 'ChildNode'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(1074,29): error TS2339: Property '_section' does not exist on type 'ChildNode'. -node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(1075,7): error TS2322: Type 'Node' is not assignable to type 'ChildNode'. -node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(1087,7): error TS2740: Type 'Node' is missing the following properties from type 'Element': assignedSlot, attributes, classList, className, and 71 more. +node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(1075,7): error TS2739: Type 'Node' is missing the following properties from type 'ChildNode': after, before, remove, replaceWith +node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(1087,7): error TS2740: Type 'ChildNode' is missing the following properties from type 'Element': assignedSlot, attributes, classList, className, and 68 more. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(1088,38): error TS2339: Property '_section' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(1090,36): error TS2339: Property '_section' does not exist on type 'Element'. -node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(1099,7): error TS2322: Type 'Node' is not assignable to type 'Element'. +node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(1099,7): error TS2740: Type 'Node' is missing the following properties from type 'Element': assignedSlot, attributes, classList, className, and 72 more. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(1100,38): error TS2339: Property '_section' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(1102,36): error TS2339: Property '_section' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(1106,22): error TS2694: Namespace 'Common' has no exported member 'Event'. @@ -6143,7 +6134,6 @@ node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(13 node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(161,5): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(219,43): error TS2694: Namespace 'Protocol' has no exported member 'Network'. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(244,54): error TS2339: Property 'traverseNextNode' does not exist on type 'HTMLElement'. -node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(245,27): error TS2693: 'ShadowRoot' only refers to a type, but is being used as a value here. node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(463,53): error TS2345: Argument of type '{ url: string; type: string; }' is not assignable to parameter of type '{ contentURL(): string; contentType(): ResourceType; contentEncoded(): Promise; requestContent(): Promise; searchInContent(query: string, caseSensitive: boolean, isRegex: boolean): Promise<...>; }'. Type '{ url: string; type: string; }' is missing the following properties from type '{ contentURL(): string; contentType(): ResourceType; contentEncoded(): Promise; requestContent(): Promise; searchInContent(query: string, caseSensitive: boolean, isRegex: boolean): Promise<...>; }': contentURL, contentType, contentEncoded, requestContent, searchInContent node_modules/chrome-devtools-frontend/front_end/extensions/ExtensionServer.js(471,22): error TS2339: Property 'valuesArray' does not exist on type 'Map; requestContent(): Promise; searchInContent(query: string, caseSensitive: boolean, isRegex: boolean): Promise<...>; }>'. @@ -6927,7 +6917,6 @@ node_modules/chrome-devtools-frontend/front_end/layer_viewer/Layers3DView.js(852 node_modules/chrome-devtools-frontend/front_end/layer_viewer/Layers3DView.js(858,13): error TS2339: Property 'image' does not exist on type 'WebGLTexture'. node_modules/chrome-devtools-frontend/front_end/layer_viewer/Layers3DView.js(861,81): error TS2339: Property 'image' does not exist on type 'WebGLTexture'. node_modules/chrome-devtools-frontend/front_end/layer_viewer/Layers3DView.js(928,26): error TS2694: Namespace 'SDK' has no exported member 'SnapshotWithRect'. -node_modules/chrome-devtools-frontend/front_end/layer_viewer/Layers3DView.js(932,39): error TS2345: Argument of type 'any[][]' is not assignable to parameter of type 'readonly [any, any][]'. node_modules/chrome-devtools-frontend/front_end/layer_viewer/Layers3DView.js(1080,24): error TS2694: Namespace 'Protocol' has no exported member 'DOM'. node_modules/chrome-devtools-frontend/front_end/layer_viewer/Layers3DView.js(1098,15): error TS2304: Cannot find name 'CSSMatrix'. node_modules/chrome-devtools-frontend/front_end/layer_viewer/Layers3DView.js(1143,19): error TS2694: Namespace 'SDK' has no exported member 'SnapshotWithRect'. @@ -8059,8 +8048,8 @@ node_modules/chrome-devtools-frontend/front_end/perf_ui/TimelineGrid.js(189,25): node_modules/chrome-devtools-frontend/front_end/perf_ui/TimelineGrid.js(196,23): error TS2339: Property '_labelElement' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/perf_ui/TimelineGrid.js(199,15): error TS2339: Property 'style' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/perf_ui/TimelineGrid.js(200,23): error TS2339: Property 'style' does not exist on type 'Element'. -node_modules/chrome-devtools-frontend/front_end/perf_ui/TimelineGrid.js(210,7): error TS2322: Type 'Node' is not assignable to type 'Element'. -node_modules/chrome-devtools-frontend/front_end/perf_ui/TimelineGrid.js(215,7): error TS2322: Type 'Node' is not assignable to type 'Element'. +node_modules/chrome-devtools-frontend/front_end/perf_ui/TimelineGrid.js(210,7): error TS2322: Type 'ChildNode' is not assignable to type 'Element'. +node_modules/chrome-devtools-frontend/front_end/perf_ui/TimelineGrid.js(215,7): error TS2322: Type 'ChildNode' is not assignable to type 'Element'. node_modules/chrome-devtools-frontend/front_end/perf_ui/TimelineGrid.js(267,21): error TS2339: Property 'DividersData' does not exist on type 'typeof TimelineGrid'. node_modules/chrome-devtools-frontend/front_end/perf_ui/TimelineGrid.js(277,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/perf_ui/TimelineGrid.js(284,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. @@ -8343,7 +8332,212 @@ node_modules/chrome-devtools-frontend/front_end/product_registry/ProductRegistry node_modules/chrome-devtools-frontend/front_end/product_registry/ProductRegistry.js(34,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. node_modules/chrome-devtools-frontend/front_end/product_registry/ProductRegistry.js(55,41): error TS2694: Namespace 'ProductRegistry.Registry' has no exported member 'ProductEntry'. node_modules/chrome-devtools-frontend/front_end/product_registry/ProductRegistry.js(72,26): error TS2339: Property 'ProductEntry' does not exist on type 'typeof Registry'. -node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(1488,1): error TS2590: Expression produces a union type that is too complex to represent. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(1559,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(1563,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(1604,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(1605,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(1606,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(1865,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(2136,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(2136,64): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(2136,86): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(2208,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(2269,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(2270,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(2322,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(2323,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(2503,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(2856,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(2857,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(2858,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(2859,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(2860,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(2861,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(2862,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(2863,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(2864,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(2865,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3126,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3572,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3573,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3574,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3575,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3576,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3747,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3748,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3770,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3771,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3772,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3773,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3774,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3775,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3776,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3780,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3819,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3826,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3873,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3874,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3957,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(3958,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(4068,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(4069,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(4138,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(4139,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(4203,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(4230,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(4260,104): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(4264,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(4265,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(4266,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(4312,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(4480,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(4832,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(4833,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(4834,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(4835,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5127,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5137,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5159,70): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5175,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5186,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5202,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5249,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5522,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5523,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5524,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5525,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5539,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5565,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5612,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5613,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5614,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5615,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5616,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5617,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5618,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5619,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5684,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5789,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5820,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5852,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5858,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5859,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5860,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5970,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5971,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(5972,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6145,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6151,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6152,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6153,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6154,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6180,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6181,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6182,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6183,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6184,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6185,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6186,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6187,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6193,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6194,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6195,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6196,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6197,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6198,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6199,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6217,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6218,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6225,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6227,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6228,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6229,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6230,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6231,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6232,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6233,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6243,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6270,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6272,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6276,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6294,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6296,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6297,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6298,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6299,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6300,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6303,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6305,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6323,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6324,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6325,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6326,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6327,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6333,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6334,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6335,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6336,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6337,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6338,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6339,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6340,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6341,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6342,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6343,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6344,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6345,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6346,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6347,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6348,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6349,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6350,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6351,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6360,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6361,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6362,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6363,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6364,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6365,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6369,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6382,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6388,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6389,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6404,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6405,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6406,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6425,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6441,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6442,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6445,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6481,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6521,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6560,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6573,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6574,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6575,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6576,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6577,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6578,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6579,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6580,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6581,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6582,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6583,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6615,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6620,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6629,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6637,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6661,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6668,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6675,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6689,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6690,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6699,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6726,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6735,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6737,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6738,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. +node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryData.js(6741,42): error TS2741: Property 'type' is missing in type '{ "product": number; }' but required in type '{ product: number; type: number; }'. node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryImpl.js(27,41): error TS2694: Namespace 'ProductRegistry.Registry' has no exported member 'ProductEntry'. node_modules/chrome-devtools-frontend/front_end/product_registry_impl/ProductRegistryImpl.js(103,67): error TS2694: Namespace 'ProductRegistry.Registry' has no exported member 'ProductEntry'. node_modules/chrome-devtools-frontend/front_end/profiler/BottomUpProfileDataGrid.js(83,15): error TS2339: Property '_remainingNodeInfos' does not exist on type 'ProfileDataGridNode'. @@ -8772,8 +8966,6 @@ node_modules/chrome-devtools-frontend/front_end/profiler/ProfileView.js(57,23): node_modules/chrome-devtools-frontend/front_end/profiler/ProfileView.js(78,46): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/profiler/ProfileView.js(79,46): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/profiler/ProfileView.js(80,45): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/profiler/ProfileView.js(84,17): error TS2345: Argument of type '(string | Element)[][]' is not assignable to parameter of type 'readonly [any, any][]'. - Type '(string | Element)[]' is missing the following properties from type '[any, any]': 0, 1 node_modules/chrome-devtools-frontend/front_end/profiler/ProfileView.js(136,59): error TS2339: Property 'profile' does not exist on type 'ProfileView'. node_modules/chrome-devtools-frontend/front_end/profiler/ProfileView.js(136,78): error TS2339: Property 'adjustedTotal' does not exist on type 'ProfileView'. node_modules/chrome-devtools-frontend/front_end/profiler/ProfileView.js(147,59): error TS2339: Property 'profile' does not exist on type 'ProfileView'. @@ -10730,7 +10922,6 @@ node_modules/chrome-devtools-frontend/front_end/source_frame/XMLView.js(54,59): node_modules/chrome-devtools-frontend/front_end/source_frame/XMLView.js(73,28): error TS2339: Property 'setSearchRegex' does not exist on type 'TreeElement'. node_modules/chrome-devtools-frontend/front_end/source_frame/XMLView.js(80,23): error TS2339: Property 'setSearchRegex' does not exist on type 'TreeElement'. node_modules/chrome-devtools-frontend/front_end/source_frame/XMLView.js(223,35): error TS2339: Property 'childElementCount' does not exist on type 'Node'. -node_modules/chrome-devtools-frontend/front_end/source_frame/XMLView.js(242,7): error TS2322: Type 'Node' is not assignable to type 'ChildNode'. node_modules/chrome-devtools-frontend/front_end/source_frame/XMLView.js(290,24): error TS2339: Property 'tagName' does not exist on type 'Node'. node_modules/chrome-devtools-frontend/front_end/source_frame/XMLView.js(296,31): error TS2339: Property 'attributes' does not exist on type 'Node'. node_modules/chrome-devtools-frontend/front_end/source_frame/XMLView.js(305,20): error TS2339: Property 'childElementCount' does not exist on type 'Node'. @@ -10860,8 +11051,6 @@ node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptBreakpointsSid node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptBreakpointsSidebarPane.js(80,71): error TS2339: Property 'uiLocation' does not exist on type 'V'. node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptBreakpointsSidebarPane.js(81,60): error TS2339: Property 'breakpoint' does not exist on type 'V'. node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptBreakpointsSidebarPane.js(82,62): error TS2339: Property 'breakpoint' does not exist on type 'V'. -node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptBreakpointsSidebarPane.js(87,7): error TS2322: Type 'Node' is not assignable to type 'ChildNode'. -node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptBreakpointsSidebarPane.js(92,7): error TS2322: Type 'Node' is not assignable to type 'ChildNode'. node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptBreakpointsSidebarPane.js(119,5): error TS2322: Type 'Promise' is not assignable to type 'Promise'. node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptBreakpointsSidebarPane.js(141,29): error TS2339: Property 'enclosingNodeOrSelfWithClass' does not exist on type 'EventTarget'. node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptBreakpointsSidebarPane.js(156,33): error TS2339: Property 'checkboxElement' does not exist on type 'EventTarget'. @@ -11345,8 +11534,6 @@ node_modules/chrome-devtools-frontend/front_end/sources_test_runner/SourcesTestR node_modules/chrome-devtools-frontend/front_end/sources_test_runner/SourcesTestRunner.js(129,11): error TS2339: Property 'pushAll' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/terminal/TerminalWidget.js(29,54): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/terminal/TerminalWidget.js(30,65): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/terminal/TerminalWidget.js(139,9): error TS2322: Type 'Node' is not assignable to type 'ChildNode'. -node_modules/chrome-devtools-frontend/front_end/terminal/TerminalWidget.js(146,7): error TS2322: Type 'Node' is not assignable to type 'ChildNode'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/addons/fit/fit.js(19,34): error TS2307: Cannot find module '../../xterm'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/addons/fit/fit.js(20,21): error TS2304: Cannot find name 'define'. node_modules/chrome-devtools-frontend/front_end/terminal/xterm.js/addons/fit/fit.js(24,5): error TS2304: Cannot find name 'define'. @@ -11500,7 +11687,6 @@ node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(683,28 node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(717,24): error TS2694: Namespace 'TestRunner' has no exported member 'CustomFormatters'. node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(748,24): error TS2694: Namespace 'TestRunner' has no exported member 'CustomFormatters'. node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(777,22): error TS2339: Property 'attributes' does not exist on type 'Node'. -node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(783,46): error TS2322: Type 'Node' is not assignable to type 'ChildNode'. node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(785,14): error TS2339: Property 'shadowRoot' does not exist on type 'Node'. node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(786,39): error TS2339: Property 'shadowRoot' does not exist on type 'Node'. node_modules/chrome-devtools-frontend/front_end/test_runner/TestRunner.js(805,12): error TS2339: Property 'shadowRoot' does not exist on type 'Node'. @@ -11742,7 +11928,7 @@ node_modules/chrome-devtools-frontend/front_end/timeline/TimelineEventOverview.j node_modules/chrome-devtools-frontend/front_end/timeline/TimelineEventOverview.js(246,68): error TS2339: Property 'peekLast' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineEventOverview.js(248,81): error TS2339: Property '_overviewIndex' does not exist on type 'TimelineCategory'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineEventOverview.js(384,7): error TS2322: Type 'Promise HTMLImageElement>' is not assignable to type 'Promise'. - Type 'new (width?: number, height?: number) => HTMLImageElement' is missing the following properties from type 'HTMLImageElement': align, alt, border, complete, and 259 more. + Type 'new (width?: number, height?: number) => HTMLImageElement' is missing the following properties from type 'HTMLImageElement': align, alt, border, complete, and 261 more. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineEventOverview.js(457,17): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineEventOverview.js(483,24): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineEventOverview.js(524,28): error TS2339: Property 'peekLast' does not exist on type 'TimelineFrame[]'. @@ -12252,7 +12438,7 @@ node_modules/chrome-devtools-frontend/front_end/timeline/TimelineUIUtils.js(1652 node_modules/chrome-devtools-frontend/front_end/timeline/TimelineUIUtils.js(1657,64): error TS2345: Argument of type 'new (width?: number, height?: number) => HTMLImageElement' is not assignable to parameter of type 'Node'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineUIUtils.js(1664,11): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineUIUtils.js(1665,67): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/timeline/TimelineUIUtils.js(1675,5): error TS2740: Type 'DocumentFragment' is missing the following properties from type 'Element': assignedSlot, attributes, classList, className, and 63 more. +node_modules/chrome-devtools-frontend/front_end/timeline/TimelineUIUtils.js(1675,5): error TS2740: Type 'DocumentFragment' is missing the following properties from type 'Element': assignedSlot, attributes, classList, className, and 64 more. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineUIUtils.js(1684,30): error TS2339: Property 'millisToString' does not exist on type 'NumberConstructor'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineUIUtils.js(1685,16): error TS2339: Property 'millisToString' does not exist on type 'NumberConstructor'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineUIUtils.js(1687,13): error TS2339: Property 'createTextChild' does not exist on type 'Element'. @@ -13027,7 +13213,7 @@ node_modules/chrome-devtools-frontend/front_end/ui/TextPrompt.js(592,35): error node_modules/chrome-devtools-frontend/front_end/ui/TextPrompt.js(601,32): error TS2339: Property 'isAncestor' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/ui/TextPrompt.js(610,54): error TS2339: Property 'isAncestor' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/ui/TextPrompt.js(622,35): error TS2339: Property 'getComponentSelection' does not exist on type 'Element'. -node_modules/chrome-devtools-frontend/front_end/ui/TextPrompt.js(627,7): error TS2740: Type 'ChildNode' is missing the following properties from type 'Element': assignedSlot, attributes, classList, className, and 67 more. +node_modules/chrome-devtools-frontend/front_end/ui/TextPrompt.js(627,7): error TS2322: Type 'ChildNode' is not assignable to type 'Element'. node_modules/chrome-devtools-frontend/front_end/ui/Toolbar.js(43,50): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/ui/Toolbar.js(48,45): error TS2339: Property 'createChild' does not exist on type 'DocumentFragment'. node_modules/chrome-devtools-frontend/front_end/ui/Toolbar.js(75,24): error TS2694: Namespace 'Common' has no exported member 'Event'. diff --git a/tests/baselines/reference/user/npm.log b/tests/baselines/reference/user/npm.log index 91a408b91d7..525a1007870 100644 --- a/tests/baselines/reference/user/npm.log +++ b/tests/baselines/reference/user/npm.log @@ -802,9 +802,9 @@ node_modules/npm/lib/utils/error-handler.js(146,27): error TS2339: Property 'con node_modules/npm/lib/utils/error-handler.js(166,14): error TS2339: Property 'code' does not exist on type 'Error'. node_modules/npm/lib/utils/error-handler.js(167,16): error TS2339: Property 'code' does not exist on type 'Error'. node_modules/npm/lib/utils/error-handler.js(168,8): error TS2339: Property 'code' does not exist on type 'Error'. -node_modules/npm/lib/utils/error-handler.js(186,40): error TS2345: Argument of type '{ (value: any, replacer?: ((key: string, value: any) => any) | undefined, space?: string | number | undefined): string; (value: any, replacer?: (string | number)[] | null | undefined, space?: string | ... 1 more ... | undefined): string; }' is not assignable to parameter of type '(value: string, index: number, array: string[]) => string'. +node_modules/npm/lib/utils/error-handler.js(186,40): error TS2345: Argument of type '{ (value: any, replacer?: ((this: any, key: string, value: any) => any) | undefined, space?: string | number | undefined): string; (value: any, replacer?: (string | number)[] | null | undefined, space?: string | ... 1 more ... | undefined): string; }' is not assignable to parameter of type '(value: string, index: number, array: string[]) => string'. Types of parameters 'replacer' and 'index' are incompatible. - Type 'number' is not assignable to type '((key: string, value: any) => any) | undefined'. + Type 'number' is not assignable to type '((this: any, key: string, value: any) => any) | undefined'. node_modules/npm/lib/utils/error-handler.js(188,33): error TS2339: Property 'version' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/utils/error-handler.js(205,11): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/utils/error-handler.js(208,18): error TS2339: Property 'code' does not exist on type 'Error'. From bbf559b9c7fd21b984d7cb538140c74e3d6a6b45 Mon Sep 17 00:00:00 2001 From: TypeScript Bot Date: Fri, 8 Feb 2019 11:03:58 -0800 Subject: [PATCH 035/149] Update user baselines (#29826) --- .../reference/user/chrome-devtools-frontend.log | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/tests/baselines/reference/user/chrome-devtools-frontend.log b/tests/baselines/reference/user/chrome-devtools-frontend.log index 3c86f06756a..55c189a92d6 100644 --- a/tests/baselines/reference/user/chrome-devtools-frontend.log +++ b/tests/baselines/reference/user/chrome-devtools-frontend.log @@ -3751,6 +3751,7 @@ node_modules/chrome-devtools-frontend/front_end/common/ParsedURL.js(152,25): err node_modules/chrome-devtools-frontend/front_end/common/ParsedURL.js(161,25): error TS2339: Property 'asParsedURL' does not exist on type 'string'. node_modules/chrome-devtools-frontend/front_end/common/ParsedURL.js(211,34): error TS2339: Property 'asParsedURL' does not exist on type 'string'. node_modules/chrome-devtools-frontend/front_end/common/ParsedURL.js(215,29): error TS2339: Property 'asParsedURL' does not exist on type 'string'. +node_modules/chrome-devtools-frontend/front_end/common/ParsedURL.js(318,32): error TS2554: Expected 0 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/common/ParsedURL.js(375,18): error TS2339: Property 'asParsedURL' does not exist on type 'String'. node_modules/chrome-devtools-frontend/front_end/common/SegmentedRange.js(48,37): error TS2339: Property 'lowerBound' does not exist on type 'Segment[]'. node_modules/chrome-devtools-frontend/front_end/common/Settings.js(49,10): error TS2339: Property 'runtime' does not exist on type 'Window'. @@ -3902,6 +3903,7 @@ node_modules/chrome-devtools-frontend/front_end/console/ConsoleContextSelector.j node_modules/chrome-devtools-frontend/front_end/console/ConsoleContextSelector.js(192,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleContextSelector.js(200,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleContextSelector.js(255,28): error TS2339: Property 'createChild' does not exist on type 'DocumentFragment'. +node_modules/chrome-devtools-frontend/front_end/console/ConsoleContextSelector.js(256,27): error TS2554: Expected 0 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/console/ConsoleContextSelector.js(257,31): error TS2339: Property 'createChild' does not exist on type 'DocumentFragment'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleContextSelector.js(264,13): error TS2339: Property 'style' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleContextSelector.js(279,14): error TS2555: Expected at least 2 arguments, but got 1. @@ -4180,6 +4182,7 @@ node_modules/chrome-devtools-frontend/front_end/console/ConsoleViewMessage.js(70 node_modules/chrome-devtools-frontend/front_end/console/ConsoleViewMessage.js(733,19): error TS2339: Property 'removeChildren' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleViewMessage.js(735,35): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleViewMessage.js(736,31): error TS2555: Expected at least 2 arguments, but got 1. +node_modules/chrome-devtools-frontend/front_end/console/ConsoleViewMessage.js(750,27): error TS2554: Expected 0 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/console/ConsoleViewMessage.js(803,34): error TS2339: Property 'style' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleViewMessage.js(804,31): error TS2339: Property 'style' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleViewMessage.js(806,43): error TS2339: Property 'style' does not exist on type 'Element'. @@ -4517,6 +4520,7 @@ node_modules/chrome-devtools-frontend/front_end/data_grid/DataGrid.js(98,48): er node_modules/chrome-devtools-frontend/front_end/data_grid/DataGrid.js(109,26): error TS2352: Conversion of type 'DataGridNode' to type 'NODE_TYPE' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. node_modules/chrome-devtools-frontend/front_end/data_grid/DataGrid.js(121,17): error TS7014: Function type, which lacks return-type annotation, implicitly has an 'any' return type. node_modules/chrome-devtools-frontend/front_end/data_grid/DataGrid.js(123,17): error TS7014: Function type, which lacks return-type annotation, implicitly has an 'any' return type. +node_modules/chrome-devtools-frontend/front_end/data_grid/DataGrid.js(134,29): error TS2554: Expected 0 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/data_grid/DataGrid.js(135,15): error TS2339: Property 'title' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/data_grid/DataGrid.js(139,15): error TS2339: Property 'title' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/data_grid/DataGrid.js(159,33): error TS2694: Namespace 'DataGrid.DataGrid' has no exported member 'ColumnDescriptor'. @@ -7751,6 +7755,7 @@ node_modules/chrome-devtools-frontend/front_end/object_ui/JavaScriptAutocomplete node_modules/chrome-devtools-frontend/front_end/object_ui/JavaScriptAutocomplete.js(471,33): error TS2339: Property 'CompletionGroup' does not exist on type 'typeof JavaScriptAutocomplete'. node_modules/chrome-devtools-frontend/front_end/object_ui/ObjectPopoverHelper.js(82,35): error TS2694: Namespace 'SDK.DebuggerModel' has no exported member 'FunctionDetails'. node_modules/chrome-devtools-frontend/front_end/object_ui/ObjectPopoverHelper.js(91,29): error TS2339: Property 'createChild' does not exist on type 'Element'. +node_modules/chrome-devtools-frontend/front_end/object_ui/ObjectPopoverHelper.js(108,23): error TS2554: Expected 0 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/object_ui/ObjectPopoverHelper.js(114,48): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/object_ui/ObjectPopoverHelper.js(129,7): error TS2722: Cannot invoke an object which is possibly 'undefined'. node_modules/chrome-devtools-frontend/front_end/object_ui/ObjectPopoverHelper.js(145,50): error TS2339: Property 'createChild' does not exist on type 'Element'. @@ -7763,6 +7768,7 @@ node_modules/chrome-devtools-frontend/front_end/object_ui/ObjectPropertiesSectio node_modules/chrome-devtools-frontend/front_end/object_ui/ObjectPropertiesSection.js(181,18): error TS2339: Property 'title' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/object_ui/ObjectPropertiesSection.js(207,22): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/object_ui/ObjectPropertiesSection.js(209,22): error TS2339: Property 'createTextChild' does not exist on type 'Element'. +node_modules/chrome-devtools-frontend/front_end/object_ui/ObjectPropertiesSection.js(209,38): error TS2554: Expected 0 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/object_ui/ObjectPropertiesSection.js(211,22): error TS2339: Property 'createTextChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/object_ui/ObjectPropertiesSection.js(263,20): error TS2339: Property 'title' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/object_ui/ObjectPropertiesSection.js(268,22): error TS2339: Property 'setTextContentTruncatedIfNeeded' does not exist on type 'Element'. @@ -8242,6 +8248,7 @@ node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(125,15): e node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(125,39): error TS2339: Property 'regexSpecialCharacters' does not exist on type 'StringConstructor'. node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(132,8): error TS2339: Property 'filterRegex' does not exist on type 'StringConstructor'. node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(133,27): error TS2339: Property 'regexSpecialCharacters' does not exist on type 'StringConstructor'. +node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(198,1): error TS2322: Type '(maxLength: number) => string' is not assignable to type '() => string'. node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(250,8): error TS2339: Property 'hashCode' does not exist on type 'StringConstructor'. node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(275,8): error TS2339: Property 'isDigitAt' does not exist on type 'StringConstructor'. node_modules/chrome-devtools-frontend/front_end/platform/utilities.js(320,8): error TS2339: Property 'naturalOrderComparator' does not exist on type 'StringConstructor'. @@ -11052,6 +11059,7 @@ node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptBreakpointsSid node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptBreakpointsSidebarPane.js(81,60): error TS2339: Property 'breakpoint' does not exist on type 'V'. node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptBreakpointsSidebarPane.js(82,62): error TS2339: Property 'breakpoint' does not exist on type 'V'. node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptBreakpointsSidebarPane.js(119,5): error TS2322: Type 'Promise' is not assignable to type 'Promise'. +node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptBreakpointsSidebarPane.js(131,38): error TS2554: Expected 0 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptBreakpointsSidebarPane.js(141,29): error TS2339: Property 'enclosingNodeOrSelfWithClass' does not exist on type 'EventTarget'. node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptBreakpointsSidebarPane.js(156,33): error TS2339: Property 'checkboxElement' does not exist on type 'EventTarget'. node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptBreakpointsSidebarPane.js(159,11): error TS2339: Property 'consume' does not exist on type 'Event'. @@ -13399,6 +13407,7 @@ node_modules/chrome-devtools-frontend/front_end/ui/UIUtils.js(1561,11): error TS node_modules/chrome-devtools-frontend/front_end/ui/UIUtils.js(1562,17): error TS2339: Property 'value' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/ui/UIUtils.js(1570,25): error TS2339: Property 'value' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/ui/UIUtils.js(1574,11): error TS2339: Property 'value' does not exist on type 'Element'. +node_modules/chrome-devtools-frontend/front_end/ui/UIUtils.js(1633,64): error TS2554: Expected 0 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/ui/UIUtils.js(1646,40): error TS2339: Property '_textWidthCache' does not exist on type '(context: CanvasRenderingContext2D, text: string) => number'. node_modules/chrome-devtools-frontend/front_end/ui/UIUtils.js(1649,25): error TS2339: Property '_textWidthCache' does not exist on type '(context: CanvasRenderingContext2D, text: string) => number'. node_modules/chrome-devtools-frontend/front_end/ui/UIUtils.js(1715,20): error TS2339: Property 'type' does not exist on type 'Element'. From 1aca1dd036928ce56173bb93e4478af6b28b464a Mon Sep 17 00:00:00 2001 From: Matt McCutchen Date: Wed, 10 Oct 2018 19:30:50 -0400 Subject: [PATCH 036/149] Make the assignability rule for conditional types require the check types and distributivity to be identical. Fixes #27118. --- src/compiler/checker.ts | 9 +- .../reference/conditionalTypes2.errors.txt | 122 +-- .../baselines/reference/conditionalTypes2.js | 121 +-- .../reference/conditionalTypes2.symbols | 870 +++++++++--------- .../reference/conditionalTypes2.types | 115 +-- .../types/conditional/conditionalTypes2.ts | 57 +- 6 files changed, 607 insertions(+), 687 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index f7cc72c534d..2d7c65fdde0 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -12693,10 +12693,11 @@ namespace ts { else if (source.flags & TypeFlags.Conditional) { if (target.flags & TypeFlags.Conditional) { // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if - // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2, - // and Y1 is related to Y2. - if (isTypeIdenticalTo((source).extendsType, (target).extendsType) && - (isRelatedTo((source).checkType, (target).checkType) || isRelatedTo((target).checkType, (source).checkType))) { + // they have the same distributivity, T1 and T2 are identical types, U1 and U2 are identical + // types, X1 is related to X2, and Y1 is related to Y2. + if ((source).root.isDistributive === (target).root.isDistributive && + isTypeIdenticalTo((source).extendsType, (target).extendsType) && + isTypeIdenticalTo((source).checkType, (target).checkType)) { if (result = isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), reportErrors)) { result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors); } diff --git a/tests/baselines/reference/conditionalTypes2.errors.txt b/tests/baselines/reference/conditionalTypes2.errors.txt index a1a23b6da18..343a0a8412c 100644 --- a/tests/baselines/reference/conditionalTypes2.errors.txt +++ b/tests/baselines/reference/conditionalTypes2.errors.txt @@ -1,29 +1,38 @@ -tests/cases/conformance/types/conditional/conditionalTypes2.ts(15,5): error TS2322: Type 'Covariant' is not assignable to type 'Covariant'. - Type 'A' is not assignable to type 'B'. -tests/cases/conformance/types/conditional/conditionalTypes2.ts(19,5): error TS2322: Type 'Contravariant' is not assignable to type 'Contravariant'. - Type 'A' is not assignable to type 'B'. -tests/cases/conformance/types/conditional/conditionalTypes2.ts(24,5): error TS2322: Type 'Invariant' is not assignable to type 'Invariant'. +tests/cases/conformance/types/conditional/conditionalTypes2.ts(16,5): error TS2322: Type 'Covariant' is not assignable to type 'Covariant'. + Types of property 'foo' are incompatible. + Type 'B extends string ? B : number' is not assignable to type 'A extends string ? A : number'. +tests/cases/conformance/types/conditional/conditionalTypes2.ts(17,5): error TS2322: Type 'Covariant' is not assignable to type 'Covariant'. + Types of property 'foo' are incompatible. + Type 'A extends string ? A : number' is not assignable to type 'B extends string ? B : number'. +tests/cases/conformance/types/conditional/conditionalTypes2.ts(21,5): error TS2322: Type 'Contravariant' is not assignable to type 'Contravariant'. + Types of property 'foo' are incompatible. + Type 'B extends string ? keyof B : number' is not assignable to type 'A extends string ? keyof A : number'. +tests/cases/conformance/types/conditional/conditionalTypes2.ts(22,5): error TS2322: Type 'Contravariant' is not assignable to type 'Contravariant'. + Types of property 'foo' are incompatible. + Type 'A extends string ? keyof A : number' is not assignable to type 'B extends string ? keyof B : number'. +tests/cases/conformance/types/conditional/conditionalTypes2.ts(26,5): error TS2322: Type 'Invariant' is not assignable to type 'Invariant'. Types of property 'foo' are incompatible. Type 'B extends string ? keyof B : B' is not assignable to type 'A extends string ? keyof A : A'. - Type 'keyof B' is not assignable to type 'keyof A'. - Type 'string | number | symbol' is not assignable to type 'keyof A'. - Type 'string' is not assignable to type 'keyof A'. -tests/cases/conformance/types/conditional/conditionalTypes2.ts(25,5): error TS2322: Type 'Invariant' is not assignable to type 'Invariant'. +tests/cases/conformance/types/conditional/conditionalTypes2.ts(27,5): error TS2322: Type 'Invariant' is not assignable to type 'Invariant'. Types of property 'foo' are incompatible. Type 'A extends string ? keyof A : A' is not assignable to type 'B extends string ? keyof B : B'. - Type 'A' is not assignable to type 'B'. -tests/cases/conformance/types/conditional/conditionalTypes2.ts(73,12): error TS2345: Argument of type 'Extract, Bar>' is not assignable to parameter of type '{ foo: string; bat: string; }'. +tests/cases/conformance/types/conditional/conditionalTypes2.ts(75,12): error TS2345: Argument of type 'Extract, Bar>' is not assignable to parameter of type '{ foo: string; bat: string; }'. Property 'bat' is missing in type 'Bar & Foo' but required in type '{ foo: string; bat: string; }'. Type 'Extract' is not assignable to type '{ foo: string; bat: string; }'. Property 'bat' is missing in type 'Bar & Foo' but required in type '{ foo: string; bat: string; }'. -tests/cases/conformance/types/conditional/conditionalTypes2.ts(74,12): error TS2345: Argument of type 'Extract' is not assignable to parameter of type '{ foo: string; bat: string; }'. +tests/cases/conformance/types/conditional/conditionalTypes2.ts(76,12): error TS2345: Argument of type 'Extract' is not assignable to parameter of type '{ foo: string; bat: string; }'. Property 'bat' is missing in type 'Foo & Bar' but required in type '{ foo: string; bat: string; }'. -tests/cases/conformance/types/conditional/conditionalTypes2.ts(75,12): error TS2345: Argument of type 'Extract2' is not assignable to parameter of type '{ foo: string; bat: string; }'. +tests/cases/conformance/types/conditional/conditionalTypes2.ts(77,12): error TS2345: Argument of type 'Extract2' is not assignable to parameter of type '{ foo: string; bat: string; }'. Type 'T extends Bar ? T : never' is not assignable to type '{ foo: string; bat: string; }'. Type 'Bar & Foo & T' is not assignable to type '{ foo: string; bat: string; }'. +tests/cases/conformance/types/conditional/conditionalTypes2.ts(165,5): error TS2322: Type 'MyElement' is not assignable to type 'MyElement'. +tests/cases/conformance/types/conditional/conditionalTypes2.ts(170,5): error TS2322: Type 'MyAcceptor' is not assignable to type 'MyAcceptor'. +tests/cases/conformance/types/conditional/conditionalTypes2.ts(177,5): error TS2322: Type 'Dist' is not assignable to type 'Aux<{ a: T; }>'. -==== tests/cases/conformance/types/conditional/conditionalTypes2.ts (7 errors) ==== +==== tests/cases/conformance/types/conditional/conditionalTypes2.ts (12 errors) ==== + // #27118: Conditional types are now invariant in the check type. + interface Covariant { foo: T extends string ? T : number; } @@ -37,19 +46,29 @@ tests/cases/conformance/types/conditional/conditionalTypes2.ts(75,12): error TS2 } function f1(a: Covariant, b: Covariant) { - a = b; + a = b; // Error + ~ +!!! error TS2322: Type 'Covariant' is not assignable to type 'Covariant'. +!!! error TS2322: Types of property 'foo' are incompatible. +!!! error TS2322: Type 'B extends string ? B : number' is not assignable to type 'A extends string ? A : number'. b = a; // Error ~ !!! error TS2322: Type 'Covariant' is not assignable to type 'Covariant'. -!!! error TS2322: Type 'A' is not assignable to type 'B'. +!!! error TS2322: Types of property 'foo' are incompatible. +!!! error TS2322: Type 'A extends string ? A : number' is not assignable to type 'B extends string ? B : number'. } function f2(a: Contravariant, b: Contravariant) { a = b; // Error ~ !!! error TS2322: Type 'Contravariant' is not assignable to type 'Contravariant'. -!!! error TS2322: Type 'A' is not assignable to type 'B'. - b = a; +!!! error TS2322: Types of property 'foo' are incompatible. +!!! error TS2322: Type 'B extends string ? keyof B : number' is not assignable to type 'A extends string ? keyof A : number'. + b = a; // Error + ~ +!!! error TS2322: Type 'Contravariant' is not assignable to type 'Contravariant'. +!!! error TS2322: Types of property 'foo' are incompatible. +!!! error TS2322: Type 'A extends string ? keyof A : number' is not assignable to type 'B extends string ? keyof B : number'. } function f3(a: Invariant, b: Invariant) { @@ -58,15 +77,11 @@ tests/cases/conformance/types/conditional/conditionalTypes2.ts(75,12): error TS2 !!! error TS2322: Type 'Invariant' is not assignable to type 'Invariant'. !!! error TS2322: Types of property 'foo' are incompatible. !!! error TS2322: Type 'B extends string ? keyof B : B' is not assignable to type 'A extends string ? keyof A : A'. -!!! error TS2322: Type 'keyof B' is not assignable to type 'keyof A'. -!!! error TS2322: Type 'string | number | symbol' is not assignable to type 'keyof A'. -!!! error TS2322: Type 'string' is not assignable to type 'keyof A'. b = a; // Error ~ !!! error TS2322: Type 'Invariant' is not assignable to type 'Invariant'. !!! error TS2322: Types of property 'foo' are incompatible. !!! error TS2322: Type 'A extends string ? keyof A : A' is not assignable to type 'B extends string ? keyof B : B'. -!!! error TS2322: Type 'A' is not assignable to type 'B'. } // Extract is a T that is known to be a Function @@ -120,13 +135,13 @@ tests/cases/conformance/types/conditional/conditionalTypes2.ts(75,12): error TS2 !!! error TS2345: Property 'bat' is missing in type 'Bar & Foo' but required in type '{ foo: string; bat: string; }'. !!! error TS2345: Type 'Extract' is not assignable to type '{ foo: string; bat: string; }'. !!! error TS2345: Property 'bat' is missing in type 'Bar & Foo' but required in type '{ foo: string; bat: string; }'. -!!! related TS2728 tests/cases/conformance/types/conditional/conditionalTypes2.ts:62:43: 'bat' is declared here. -!!! related TS2728 tests/cases/conformance/types/conditional/conditionalTypes2.ts:62:43: 'bat' is declared here. +!!! related TS2728 tests/cases/conformance/types/conditional/conditionalTypes2.ts:64:43: 'bat' is declared here. +!!! related TS2728 tests/cases/conformance/types/conditional/conditionalTypes2.ts:64:43: 'bat' is declared here. fooBat(y); // Error ~ !!! error TS2345: Argument of type 'Extract' is not assignable to parameter of type '{ foo: string; bat: string; }'. !!! error TS2345: Property 'bat' is missing in type 'Foo & Bar' but required in type '{ foo: string; bat: string; }'. -!!! related TS2728 tests/cases/conformance/types/conditional/conditionalTypes2.ts:62:43: 'bat' is declared here. +!!! related TS2728 tests/cases/conformance/types/conditional/conditionalTypes2.ts:64:43: 'bat' is declared here. fooBat(z); // Error ~ !!! error TS2345: Argument of type 'Extract2' is not assignable to parameter of type '{ foo: string; bat: string; }'. @@ -134,38 +149,6 @@ tests/cases/conformance/types/conditional/conditionalTypes2.ts(75,12): error TS2 !!! error TS2345: Type 'Bar & Foo & T' is not assignable to type '{ foo: string; bat: string; }'. } - // Repros from #22860 - - class Opt { - toVector(): Vector { - return undefined; - } - } - - interface Seq { - tail(): Opt>; - } - - class Vector implements Seq { - tail(): Opt> { - return undefined; - } - partition2(predicate:(v:T)=>v is U): [Vector,Vector>]; - partition2(predicate:(x:T)=>boolean): [Vector,Vector]; - partition2(predicate:(v:T)=>boolean): [Vector,Vector] { - return undefined; - } - } - - interface A1 { - bat: B1>; - } - - interface B1 extends A1 { - bat: B1>; - boom: T extends any ? true : true - } - // Repro from #22899 declare function toString1(value: object | Function): string ; @@ -246,4 +229,29 @@ tests/cases/conformance/types/conditional/conditionalTypes2.ts(75,12): error TS2 }; type PCCA = ProductComplementComplement['a']; type PCCB = ProductComplementComplement['b']; + + // Repros from #27118 + + type MyElement = [A] extends [[infer E]] ? E : never; + function oops(arg: MyElement): MyElement { + return arg; // Unsound, should be error + ~~~~~~~~~~~ +!!! error TS2322: Type 'MyElement' is not assignable to type 'MyElement'. + } + + type MyAcceptor = [A] extends [[infer E]] ? (arg: E) => void : never; + function oops2(arg: MyAcceptor): MyAcceptor { + return arg; // Unsound, should be error + ~~~~~~~~~~~ +!!! error TS2322: Type 'MyAcceptor' is not assignable to type 'MyAcceptor'. + } + + type Dist = T extends number ? number : string; + type Aux = A["a"] extends number ? number : string; + type Nondist = Aux<{a: T}>; + function oops3(arg: Dist): Nondist { + return arg; // Unsound, should be error + ~~~~~~~~~~~ +!!! error TS2322: Type 'Dist' is not assignable to type 'Aux<{ a: T; }>'. + } \ No newline at end of file diff --git a/tests/baselines/reference/conditionalTypes2.js b/tests/baselines/reference/conditionalTypes2.js index 4f4f35e821a..c59c996711d 100644 --- a/tests/baselines/reference/conditionalTypes2.js +++ b/tests/baselines/reference/conditionalTypes2.js @@ -1,4 +1,6 @@ //// [conditionalTypes2.ts] +// #27118: Conditional types are now invariant in the check type. + interface Covariant { foo: T extends string ? T : number; } @@ -12,13 +14,13 @@ interface Invariant { } function f1(a: Covariant, b: Covariant) { - a = b; + a = b; // Error b = a; // Error } function f2(a: Contravariant, b: Contravariant) { a = b; // Error - b = a; + b = a; // Error } function f3(a: Invariant, b: Invariant) { @@ -76,38 +78,6 @@ function f21(x: Extract, Bar>, y: Extract, z: E fooBat(z); // Error } -// Repros from #22860 - -class Opt { - toVector(): Vector { - return undefined; - } -} - -interface Seq { - tail(): Opt>; -} - -class Vector implements Seq { - tail(): Opt> { - return undefined; - } - partition2(predicate:(v:T)=>v is U): [Vector,Vector>]; - partition2(predicate:(x:T)=>boolean): [Vector,Vector]; - partition2(predicate:(v:T)=>boolean): [Vector,Vector] { - return undefined; - } -} - -interface A1 { - bat: B1>; -} - -interface B1 extends A1 { - bat: B1>; - boom: T extends any ? true : true -} - // Repro from #22899 declare function toString1(value: object | Function): string ; @@ -188,17 +158,37 @@ type ProductComplementComplement = { }; type PCCA = ProductComplementComplement['a']; type PCCB = ProductComplementComplement['b']; + +// Repros from #27118 + +type MyElement = [A] extends [[infer E]] ? E : never; +function oops(arg: MyElement): MyElement { + return arg; // Unsound, should be error +} + +type MyAcceptor = [A] extends [[infer E]] ? (arg: E) => void : never; +function oops2(arg: MyAcceptor): MyAcceptor { + return arg; // Unsound, should be error +} + +type Dist = T extends number ? number : string; +type Aux = A["a"] extends number ? number : string; +type Nondist = Aux<{a: T}>; +function oops3(arg: Dist): Nondist { + return arg; // Unsound, should be error +} //// [conditionalTypes2.js] "use strict"; +// #27118: Conditional types are now invariant in the check type. function f1(a, b) { - a = b; + a = b; // Error b = a; // Error } function f2(a, b) { a = b; // Error - b = a; + b = a; // Error } function f3(a, b) { a = b; // Error @@ -239,32 +229,21 @@ function f21(x, y, z) { fooBat(y); // Error fooBat(z); // Error } -// Repros from #22860 -var Opt = /** @class */ (function () { - function Opt() { - } - Opt.prototype.toVector = function () { - return undefined; - }; - return Opt; -}()); -var Vector = /** @class */ (function () { - function Vector() { - } - Vector.prototype.tail = function () { - return undefined; - }; - Vector.prototype.partition2 = function (predicate) { - return undefined; - }; - return Vector; -}()); function foo(value) { if (isFunction(value)) { toString1(value); toString2(value); } } +function oops(arg) { + return arg; // Unsound, should be error +} +function oops2(arg) { + return arg; // Unsound, should be error +} +function oops3(arg) { + return arg; // Unsound, should be error +} //// [conditionalTypes2.d.ts] @@ -302,24 +281,6 @@ declare function fooBat(x: { declare type Extract2 = T extends U ? T extends V ? T : never : never; declare function f20(x: Extract, Bar>, y: Extract, z: Extract2): void; declare function f21(x: Extract, Bar>, y: Extract, z: Extract2): void; -declare class Opt { - toVector(): Vector; -} -interface Seq { - tail(): Opt>; -} -declare class Vector implements Seq { - tail(): Opt>; - partition2(predicate: (v: T) => v is U): [Vector, Vector>]; - partition2(predicate: (x: T) => boolean): [Vector, Vector]; -} -interface A1 { - bat: B1>; -} -interface B1 extends A1 { - bat: B1>; - boom: T extends any ? true : true; -} declare function toString1(value: object | Function): string; declare function toString2(value: Function): string; declare function foo(value: T): void; @@ -392,3 +353,15 @@ declare type ProductComplementComplement = { }; declare type PCCA = ProductComplementComplement['a']; declare type PCCB = ProductComplementComplement['b']; +declare type MyElement = [A] extends [[infer E]] ? E : never; +declare function oops(arg: MyElement): MyElement; +declare type MyAcceptor = [A] extends [[infer E]] ? (arg: E) => void : never; +declare function oops2(arg: MyAcceptor): MyAcceptor; +declare type Dist = T extends number ? number : string; +declare type Aux = A["a"] extends number ? number : string; +declare type Nondist = Aux<{ + a: T; +}>; +declare function oops3(arg: Dist): Nondist; diff --git a/tests/baselines/reference/conditionalTypes2.symbols b/tests/baselines/reference/conditionalTypes2.symbols index b164d26e450..7bbf837eece 100644 --- a/tests/baselines/reference/conditionalTypes2.symbols +++ b/tests/baselines/reference/conditionalTypes2.symbols @@ -1,687 +1,655 @@ === tests/cases/conformance/types/conditional/conditionalTypes2.ts === +// #27118: Conditional types are now invariant in the check type. + interface Covariant { >Covariant : Symbol(Covariant, Decl(conditionalTypes2.ts, 0, 0)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 0, 20)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 2, 20)) foo: T extends string ? T : number; ->foo : Symbol(Covariant.foo, Decl(conditionalTypes2.ts, 0, 24)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 0, 20)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 0, 20)) +>foo : Symbol(Covariant.foo, Decl(conditionalTypes2.ts, 2, 24)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 2, 20)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 2, 20)) } interface Contravariant { ->Contravariant : Symbol(Contravariant, Decl(conditionalTypes2.ts, 2, 1)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 4, 24)) +>Contravariant : Symbol(Contravariant, Decl(conditionalTypes2.ts, 4, 1)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 6, 24)) foo: T extends string ? keyof T : number; ->foo : Symbol(Contravariant.foo, Decl(conditionalTypes2.ts, 4, 28)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 4, 24)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 4, 24)) +>foo : Symbol(Contravariant.foo, Decl(conditionalTypes2.ts, 6, 28)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 6, 24)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 6, 24)) } interface Invariant { ->Invariant : Symbol(Invariant, Decl(conditionalTypes2.ts, 6, 1)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 8, 20)) +>Invariant : Symbol(Invariant, Decl(conditionalTypes2.ts, 8, 1)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 10, 20)) foo: T extends string ? keyof T : T; ->foo : Symbol(Invariant.foo, Decl(conditionalTypes2.ts, 8, 24)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 8, 20)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 8, 20)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 8, 20)) +>foo : Symbol(Invariant.foo, Decl(conditionalTypes2.ts, 10, 24)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 10, 20)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 10, 20)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 10, 20)) } function f1(a: Covariant, b: Covariant) { ->f1 : Symbol(f1, Decl(conditionalTypes2.ts, 10, 1)) ->A : Symbol(A, Decl(conditionalTypes2.ts, 12, 12)) ->B : Symbol(B, Decl(conditionalTypes2.ts, 12, 14)) ->A : Symbol(A, Decl(conditionalTypes2.ts, 12, 12)) ->a : Symbol(a, Decl(conditionalTypes2.ts, 12, 28)) +>f1 : Symbol(f1, Decl(conditionalTypes2.ts, 12, 1)) +>A : Symbol(A, Decl(conditionalTypes2.ts, 14, 12)) +>B : Symbol(B, Decl(conditionalTypes2.ts, 14, 14)) +>A : Symbol(A, Decl(conditionalTypes2.ts, 14, 12)) +>a : Symbol(a, Decl(conditionalTypes2.ts, 14, 28)) >Covariant : Symbol(Covariant, Decl(conditionalTypes2.ts, 0, 0)) ->A : Symbol(A, Decl(conditionalTypes2.ts, 12, 12)) ->b : Symbol(b, Decl(conditionalTypes2.ts, 12, 44)) +>A : Symbol(A, Decl(conditionalTypes2.ts, 14, 12)) +>b : Symbol(b, Decl(conditionalTypes2.ts, 14, 44)) >Covariant : Symbol(Covariant, Decl(conditionalTypes2.ts, 0, 0)) ->B : Symbol(B, Decl(conditionalTypes2.ts, 12, 14)) +>B : Symbol(B, Decl(conditionalTypes2.ts, 14, 14)) - a = b; ->a : Symbol(a, Decl(conditionalTypes2.ts, 12, 28)) ->b : Symbol(b, Decl(conditionalTypes2.ts, 12, 44)) + a = b; // Error +>a : Symbol(a, Decl(conditionalTypes2.ts, 14, 28)) +>b : Symbol(b, Decl(conditionalTypes2.ts, 14, 44)) b = a; // Error ->b : Symbol(b, Decl(conditionalTypes2.ts, 12, 44)) ->a : Symbol(a, Decl(conditionalTypes2.ts, 12, 28)) +>b : Symbol(b, Decl(conditionalTypes2.ts, 14, 44)) +>a : Symbol(a, Decl(conditionalTypes2.ts, 14, 28)) } function f2(a: Contravariant, b: Contravariant) { ->f2 : Symbol(f2, Decl(conditionalTypes2.ts, 15, 1)) ->A : Symbol(A, Decl(conditionalTypes2.ts, 17, 12)) ->B : Symbol(B, Decl(conditionalTypes2.ts, 17, 14)) ->A : Symbol(A, Decl(conditionalTypes2.ts, 17, 12)) ->a : Symbol(a, Decl(conditionalTypes2.ts, 17, 28)) ->Contravariant : Symbol(Contravariant, Decl(conditionalTypes2.ts, 2, 1)) ->A : Symbol(A, Decl(conditionalTypes2.ts, 17, 12)) ->b : Symbol(b, Decl(conditionalTypes2.ts, 17, 48)) ->Contravariant : Symbol(Contravariant, Decl(conditionalTypes2.ts, 2, 1)) ->B : Symbol(B, Decl(conditionalTypes2.ts, 17, 14)) +>f2 : Symbol(f2, Decl(conditionalTypes2.ts, 17, 1)) +>A : Symbol(A, Decl(conditionalTypes2.ts, 19, 12)) +>B : Symbol(B, Decl(conditionalTypes2.ts, 19, 14)) +>A : Symbol(A, Decl(conditionalTypes2.ts, 19, 12)) +>a : Symbol(a, Decl(conditionalTypes2.ts, 19, 28)) +>Contravariant : Symbol(Contravariant, Decl(conditionalTypes2.ts, 4, 1)) +>A : Symbol(A, Decl(conditionalTypes2.ts, 19, 12)) +>b : Symbol(b, Decl(conditionalTypes2.ts, 19, 48)) +>Contravariant : Symbol(Contravariant, Decl(conditionalTypes2.ts, 4, 1)) +>B : Symbol(B, Decl(conditionalTypes2.ts, 19, 14)) a = b; // Error ->a : Symbol(a, Decl(conditionalTypes2.ts, 17, 28)) ->b : Symbol(b, Decl(conditionalTypes2.ts, 17, 48)) +>a : Symbol(a, Decl(conditionalTypes2.ts, 19, 28)) +>b : Symbol(b, Decl(conditionalTypes2.ts, 19, 48)) - b = a; ->b : Symbol(b, Decl(conditionalTypes2.ts, 17, 48)) ->a : Symbol(a, Decl(conditionalTypes2.ts, 17, 28)) + b = a; // Error +>b : Symbol(b, Decl(conditionalTypes2.ts, 19, 48)) +>a : Symbol(a, Decl(conditionalTypes2.ts, 19, 28)) } function f3(a: Invariant, b: Invariant) { ->f3 : Symbol(f3, Decl(conditionalTypes2.ts, 20, 1)) ->A : Symbol(A, Decl(conditionalTypes2.ts, 22, 12)) ->B : Symbol(B, Decl(conditionalTypes2.ts, 22, 14)) ->A : Symbol(A, Decl(conditionalTypes2.ts, 22, 12)) ->a : Symbol(a, Decl(conditionalTypes2.ts, 22, 28)) ->Invariant : Symbol(Invariant, Decl(conditionalTypes2.ts, 6, 1)) ->A : Symbol(A, Decl(conditionalTypes2.ts, 22, 12)) ->b : Symbol(b, Decl(conditionalTypes2.ts, 22, 44)) ->Invariant : Symbol(Invariant, Decl(conditionalTypes2.ts, 6, 1)) ->B : Symbol(B, Decl(conditionalTypes2.ts, 22, 14)) +>f3 : Symbol(f3, Decl(conditionalTypes2.ts, 22, 1)) +>A : Symbol(A, Decl(conditionalTypes2.ts, 24, 12)) +>B : Symbol(B, Decl(conditionalTypes2.ts, 24, 14)) +>A : Symbol(A, Decl(conditionalTypes2.ts, 24, 12)) +>a : Symbol(a, Decl(conditionalTypes2.ts, 24, 28)) +>Invariant : Symbol(Invariant, Decl(conditionalTypes2.ts, 8, 1)) +>A : Symbol(A, Decl(conditionalTypes2.ts, 24, 12)) +>b : Symbol(b, Decl(conditionalTypes2.ts, 24, 44)) +>Invariant : Symbol(Invariant, Decl(conditionalTypes2.ts, 8, 1)) +>B : Symbol(B, Decl(conditionalTypes2.ts, 24, 14)) a = b; // Error ->a : Symbol(a, Decl(conditionalTypes2.ts, 22, 28)) ->b : Symbol(b, Decl(conditionalTypes2.ts, 22, 44)) +>a : Symbol(a, Decl(conditionalTypes2.ts, 24, 28)) +>b : Symbol(b, Decl(conditionalTypes2.ts, 24, 44)) b = a; // Error ->b : Symbol(b, Decl(conditionalTypes2.ts, 22, 44)) ->a : Symbol(a, Decl(conditionalTypes2.ts, 22, 28)) +>b : Symbol(b, Decl(conditionalTypes2.ts, 24, 44)) +>a : Symbol(a, Decl(conditionalTypes2.ts, 24, 28)) } // Extract is a T that is known to be a Function function isFunction(value: T): value is Extract { ->isFunction : Symbol(isFunction, Decl(conditionalTypes2.ts, 25, 1)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 28, 20)) ->value : Symbol(value, Decl(conditionalTypes2.ts, 28, 23)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 28, 20)) ->value : Symbol(value, Decl(conditionalTypes2.ts, 28, 23)) +>isFunction : Symbol(isFunction, Decl(conditionalTypes2.ts, 27, 1)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 30, 20)) +>value : Symbol(value, Decl(conditionalTypes2.ts, 30, 23)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 30, 20)) +>value : Symbol(value, Decl(conditionalTypes2.ts, 30, 23)) >Extract : Symbol(Extract, Decl(lib.es5.d.ts, --, --)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 28, 20)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 30, 20)) >Function : Symbol(Function, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) return typeof value === "function"; ->value : Symbol(value, Decl(conditionalTypes2.ts, 28, 23)) +>value : Symbol(value, Decl(conditionalTypes2.ts, 30, 23)) } function getFunction(item: T) { ->getFunction : Symbol(getFunction, Decl(conditionalTypes2.ts, 30, 1)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 32, 21)) ->item : Symbol(item, Decl(conditionalTypes2.ts, 32, 24)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 32, 21)) +>getFunction : Symbol(getFunction, Decl(conditionalTypes2.ts, 32, 1)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 34, 21)) +>item : Symbol(item, Decl(conditionalTypes2.ts, 34, 24)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 34, 21)) if (isFunction(item)) { ->isFunction : Symbol(isFunction, Decl(conditionalTypes2.ts, 25, 1)) ->item : Symbol(item, Decl(conditionalTypes2.ts, 32, 24)) +>isFunction : Symbol(isFunction, Decl(conditionalTypes2.ts, 27, 1)) +>item : Symbol(item, Decl(conditionalTypes2.ts, 34, 24)) return item; ->item : Symbol(item, Decl(conditionalTypes2.ts, 32, 24)) +>item : Symbol(item, Decl(conditionalTypes2.ts, 34, 24)) } throw new Error(); >Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) } function f10(x: T) { ->f10 : Symbol(f10, Decl(conditionalTypes2.ts, 37, 1)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 39, 13)) ->x : Symbol(x, Decl(conditionalTypes2.ts, 39, 16)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 39, 13)) +>f10 : Symbol(f10, Decl(conditionalTypes2.ts, 39, 1)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 41, 13)) +>x : Symbol(x, Decl(conditionalTypes2.ts, 41, 16)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 41, 13)) if (isFunction(x)) { ->isFunction : Symbol(isFunction, Decl(conditionalTypes2.ts, 25, 1)) ->x : Symbol(x, Decl(conditionalTypes2.ts, 39, 16)) +>isFunction : Symbol(isFunction, Decl(conditionalTypes2.ts, 27, 1)) +>x : Symbol(x, Decl(conditionalTypes2.ts, 41, 16)) const f: Function = x; ->f : Symbol(f, Decl(conditionalTypes2.ts, 41, 13)) +>f : Symbol(f, Decl(conditionalTypes2.ts, 43, 13)) >Function : Symbol(Function, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) ->x : Symbol(x, Decl(conditionalTypes2.ts, 39, 16)) +>x : Symbol(x, Decl(conditionalTypes2.ts, 41, 16)) const t: T = x; ->t : Symbol(t, Decl(conditionalTypes2.ts, 42, 13)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 39, 13)) ->x : Symbol(x, Decl(conditionalTypes2.ts, 39, 16)) +>t : Symbol(t, Decl(conditionalTypes2.ts, 44, 13)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 41, 13)) +>x : Symbol(x, Decl(conditionalTypes2.ts, 41, 16)) } } function f11(x: string | (() => string) | undefined) { ->f11 : Symbol(f11, Decl(conditionalTypes2.ts, 44, 1)) ->x : Symbol(x, Decl(conditionalTypes2.ts, 46, 13)) +>f11 : Symbol(f11, Decl(conditionalTypes2.ts, 46, 1)) +>x : Symbol(x, Decl(conditionalTypes2.ts, 48, 13)) if (isFunction(x)) { ->isFunction : Symbol(isFunction, Decl(conditionalTypes2.ts, 25, 1)) ->x : Symbol(x, Decl(conditionalTypes2.ts, 46, 13)) +>isFunction : Symbol(isFunction, Decl(conditionalTypes2.ts, 27, 1)) +>x : Symbol(x, Decl(conditionalTypes2.ts, 48, 13)) x(); ->x : Symbol(x, Decl(conditionalTypes2.ts, 46, 13)) +>x : Symbol(x, Decl(conditionalTypes2.ts, 48, 13)) } } function f12(x: string | (() => string) | undefined) { ->f12 : Symbol(f12, Decl(conditionalTypes2.ts, 50, 1)) ->x : Symbol(x, Decl(conditionalTypes2.ts, 52, 13)) +>f12 : Symbol(f12, Decl(conditionalTypes2.ts, 52, 1)) +>x : Symbol(x, Decl(conditionalTypes2.ts, 54, 13)) const f = getFunction(x); // () => string ->f : Symbol(f, Decl(conditionalTypes2.ts, 53, 9)) ->getFunction : Symbol(getFunction, Decl(conditionalTypes2.ts, 30, 1)) ->x : Symbol(x, Decl(conditionalTypes2.ts, 52, 13)) +>f : Symbol(f, Decl(conditionalTypes2.ts, 55, 9)) +>getFunction : Symbol(getFunction, Decl(conditionalTypes2.ts, 32, 1)) +>x : Symbol(x, Decl(conditionalTypes2.ts, 54, 13)) f(); ->f : Symbol(f, Decl(conditionalTypes2.ts, 53, 9)) +>f : Symbol(f, Decl(conditionalTypes2.ts, 55, 9)) } type Foo = { foo: string }; ->Foo : Symbol(Foo, Decl(conditionalTypes2.ts, 55, 1)) ->foo : Symbol(foo, Decl(conditionalTypes2.ts, 57, 12)) +>Foo : Symbol(Foo, Decl(conditionalTypes2.ts, 57, 1)) +>foo : Symbol(foo, Decl(conditionalTypes2.ts, 59, 12)) type Bar = { bar: string }; ->Bar : Symbol(Bar, Decl(conditionalTypes2.ts, 57, 27)) ->bar : Symbol(bar, Decl(conditionalTypes2.ts, 58, 12)) +>Bar : Symbol(Bar, Decl(conditionalTypes2.ts, 59, 27)) +>bar : Symbol(bar, Decl(conditionalTypes2.ts, 60, 12)) declare function fooBar(x: { foo: string, bar: string }): void; ->fooBar : Symbol(fooBar, Decl(conditionalTypes2.ts, 58, 27)) ->x : Symbol(x, Decl(conditionalTypes2.ts, 60, 24)) ->foo : Symbol(foo, Decl(conditionalTypes2.ts, 60, 28)) ->bar : Symbol(bar, Decl(conditionalTypes2.ts, 60, 41)) +>fooBar : Symbol(fooBar, Decl(conditionalTypes2.ts, 60, 27)) +>x : Symbol(x, Decl(conditionalTypes2.ts, 62, 24)) +>foo : Symbol(foo, Decl(conditionalTypes2.ts, 62, 28)) +>bar : Symbol(bar, Decl(conditionalTypes2.ts, 62, 41)) declare function fooBat(x: { foo: string, bat: string }): void; ->fooBat : Symbol(fooBat, Decl(conditionalTypes2.ts, 60, 63)) ->x : Symbol(x, Decl(conditionalTypes2.ts, 61, 24)) ->foo : Symbol(foo, Decl(conditionalTypes2.ts, 61, 28)) ->bat : Symbol(bat, Decl(conditionalTypes2.ts, 61, 41)) +>fooBat : Symbol(fooBat, Decl(conditionalTypes2.ts, 62, 63)) +>x : Symbol(x, Decl(conditionalTypes2.ts, 63, 24)) +>foo : Symbol(foo, Decl(conditionalTypes2.ts, 63, 28)) +>bat : Symbol(bat, Decl(conditionalTypes2.ts, 63, 41)) type Extract2 = T extends U ? T extends V ? T : never : never; ->Extract2 : Symbol(Extract2, Decl(conditionalTypes2.ts, 61, 63)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 63, 14)) ->U : Symbol(U, Decl(conditionalTypes2.ts, 63, 16)) ->V : Symbol(V, Decl(conditionalTypes2.ts, 63, 19)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 63, 14)) ->U : Symbol(U, Decl(conditionalTypes2.ts, 63, 16)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 63, 14)) ->V : Symbol(V, Decl(conditionalTypes2.ts, 63, 19)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 63, 14)) +>Extract2 : Symbol(Extract2, Decl(conditionalTypes2.ts, 63, 63)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 65, 14)) +>U : Symbol(U, Decl(conditionalTypes2.ts, 65, 16)) +>V : Symbol(V, Decl(conditionalTypes2.ts, 65, 19)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 65, 14)) +>U : Symbol(U, Decl(conditionalTypes2.ts, 65, 16)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 65, 14)) +>V : Symbol(V, Decl(conditionalTypes2.ts, 65, 19)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 65, 14)) function f20(x: Extract, Bar>, y: Extract, z: Extract2) { ->f20 : Symbol(f20, Decl(conditionalTypes2.ts, 63, 71)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 65, 13)) ->x : Symbol(x, Decl(conditionalTypes2.ts, 65, 16)) +>f20 : Symbol(f20, Decl(conditionalTypes2.ts, 65, 71)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 67, 13)) +>x : Symbol(x, Decl(conditionalTypes2.ts, 67, 16)) >Extract : Symbol(Extract, Decl(lib.es5.d.ts, --, --)) >Extract : Symbol(Extract, Decl(lib.es5.d.ts, --, --)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 65, 13)) ->Foo : Symbol(Foo, Decl(conditionalTypes2.ts, 55, 1)) ->Bar : Symbol(Bar, Decl(conditionalTypes2.ts, 57, 27)) ->y : Symbol(y, Decl(conditionalTypes2.ts, 65, 49)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 67, 13)) +>Foo : Symbol(Foo, Decl(conditionalTypes2.ts, 57, 1)) +>Bar : Symbol(Bar, Decl(conditionalTypes2.ts, 59, 27)) +>y : Symbol(y, Decl(conditionalTypes2.ts, 67, 49)) >Extract : Symbol(Extract, Decl(lib.es5.d.ts, --, --)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 65, 13)) ->Foo : Symbol(Foo, Decl(conditionalTypes2.ts, 55, 1)) ->Bar : Symbol(Bar, Decl(conditionalTypes2.ts, 57, 27)) ->z : Symbol(z, Decl(conditionalTypes2.ts, 65, 75)) ->Extract2 : Symbol(Extract2, Decl(conditionalTypes2.ts, 61, 63)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 65, 13)) ->Foo : Symbol(Foo, Decl(conditionalTypes2.ts, 55, 1)) ->Bar : Symbol(Bar, Decl(conditionalTypes2.ts, 57, 27)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 67, 13)) +>Foo : Symbol(Foo, Decl(conditionalTypes2.ts, 57, 1)) +>Bar : Symbol(Bar, Decl(conditionalTypes2.ts, 59, 27)) +>z : Symbol(z, Decl(conditionalTypes2.ts, 67, 75)) +>Extract2 : Symbol(Extract2, Decl(conditionalTypes2.ts, 63, 63)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 67, 13)) +>Foo : Symbol(Foo, Decl(conditionalTypes2.ts, 57, 1)) +>Bar : Symbol(Bar, Decl(conditionalTypes2.ts, 59, 27)) fooBar(x); ->fooBar : Symbol(fooBar, Decl(conditionalTypes2.ts, 58, 27)) ->x : Symbol(x, Decl(conditionalTypes2.ts, 65, 16)) +>fooBar : Symbol(fooBar, Decl(conditionalTypes2.ts, 60, 27)) +>x : Symbol(x, Decl(conditionalTypes2.ts, 67, 16)) fooBar(y); ->fooBar : Symbol(fooBar, Decl(conditionalTypes2.ts, 58, 27)) ->y : Symbol(y, Decl(conditionalTypes2.ts, 65, 49)) +>fooBar : Symbol(fooBar, Decl(conditionalTypes2.ts, 60, 27)) +>y : Symbol(y, Decl(conditionalTypes2.ts, 67, 49)) fooBar(z); ->fooBar : Symbol(fooBar, Decl(conditionalTypes2.ts, 58, 27)) ->z : Symbol(z, Decl(conditionalTypes2.ts, 65, 75)) +>fooBar : Symbol(fooBar, Decl(conditionalTypes2.ts, 60, 27)) +>z : Symbol(z, Decl(conditionalTypes2.ts, 67, 75)) } function f21(x: Extract, Bar>, y: Extract, z: Extract2) { ->f21 : Symbol(f21, Decl(conditionalTypes2.ts, 69, 1)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 71, 13)) ->x : Symbol(x, Decl(conditionalTypes2.ts, 71, 16)) +>f21 : Symbol(f21, Decl(conditionalTypes2.ts, 71, 1)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 73, 13)) +>x : Symbol(x, Decl(conditionalTypes2.ts, 73, 16)) >Extract : Symbol(Extract, Decl(lib.es5.d.ts, --, --)) >Extract : Symbol(Extract, Decl(lib.es5.d.ts, --, --)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 71, 13)) ->Foo : Symbol(Foo, Decl(conditionalTypes2.ts, 55, 1)) ->Bar : Symbol(Bar, Decl(conditionalTypes2.ts, 57, 27)) ->y : Symbol(y, Decl(conditionalTypes2.ts, 71, 49)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 73, 13)) +>Foo : Symbol(Foo, Decl(conditionalTypes2.ts, 57, 1)) +>Bar : Symbol(Bar, Decl(conditionalTypes2.ts, 59, 27)) +>y : Symbol(y, Decl(conditionalTypes2.ts, 73, 49)) >Extract : Symbol(Extract, Decl(lib.es5.d.ts, --, --)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 71, 13)) ->Foo : Symbol(Foo, Decl(conditionalTypes2.ts, 55, 1)) ->Bar : Symbol(Bar, Decl(conditionalTypes2.ts, 57, 27)) ->z : Symbol(z, Decl(conditionalTypes2.ts, 71, 75)) ->Extract2 : Symbol(Extract2, Decl(conditionalTypes2.ts, 61, 63)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 71, 13)) ->Foo : Symbol(Foo, Decl(conditionalTypes2.ts, 55, 1)) ->Bar : Symbol(Bar, Decl(conditionalTypes2.ts, 57, 27)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 73, 13)) +>Foo : Symbol(Foo, Decl(conditionalTypes2.ts, 57, 1)) +>Bar : Symbol(Bar, Decl(conditionalTypes2.ts, 59, 27)) +>z : Symbol(z, Decl(conditionalTypes2.ts, 73, 75)) +>Extract2 : Symbol(Extract2, Decl(conditionalTypes2.ts, 63, 63)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 73, 13)) +>Foo : Symbol(Foo, Decl(conditionalTypes2.ts, 57, 1)) +>Bar : Symbol(Bar, Decl(conditionalTypes2.ts, 59, 27)) fooBat(x); // Error ->fooBat : Symbol(fooBat, Decl(conditionalTypes2.ts, 60, 63)) ->x : Symbol(x, Decl(conditionalTypes2.ts, 71, 16)) +>fooBat : Symbol(fooBat, Decl(conditionalTypes2.ts, 62, 63)) +>x : Symbol(x, Decl(conditionalTypes2.ts, 73, 16)) fooBat(y); // Error ->fooBat : Symbol(fooBat, Decl(conditionalTypes2.ts, 60, 63)) ->y : Symbol(y, Decl(conditionalTypes2.ts, 71, 49)) +>fooBat : Symbol(fooBat, Decl(conditionalTypes2.ts, 62, 63)) +>y : Symbol(y, Decl(conditionalTypes2.ts, 73, 49)) fooBat(z); // Error ->fooBat : Symbol(fooBat, Decl(conditionalTypes2.ts, 60, 63)) ->z : Symbol(z, Decl(conditionalTypes2.ts, 71, 75)) -} - -// Repros from #22860 - -class Opt { ->Opt : Symbol(Opt, Decl(conditionalTypes2.ts, 75, 1)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 79, 10)) - - toVector(): Vector { ->toVector : Symbol(Opt.toVector, Decl(conditionalTypes2.ts, 79, 14)) ->Vector : Symbol(Vector, Decl(conditionalTypes2.ts, 87, 1)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 79, 10)) - - return undefined; ->undefined : Symbol(undefined) - } -} - -interface Seq { ->Seq : Symbol(Seq, Decl(conditionalTypes2.ts, 83, 1)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 85, 14)) - - tail(): Opt>; ->tail : Symbol(Seq.tail, Decl(conditionalTypes2.ts, 85, 18)) ->Opt : Symbol(Opt, Decl(conditionalTypes2.ts, 75, 1)) ->Seq : Symbol(Seq, Decl(conditionalTypes2.ts, 83, 1)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 85, 14)) -} - -class Vector implements Seq { ->Vector : Symbol(Vector, Decl(conditionalTypes2.ts, 87, 1)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 89, 13)) ->Seq : Symbol(Seq, Decl(conditionalTypes2.ts, 83, 1)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 89, 13)) - - tail(): Opt> { ->tail : Symbol(Vector.tail, Decl(conditionalTypes2.ts, 89, 35)) ->Opt : Symbol(Opt, Decl(conditionalTypes2.ts, 75, 1)) ->Vector : Symbol(Vector, Decl(conditionalTypes2.ts, 87, 1)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 89, 13)) - - return undefined; ->undefined : Symbol(undefined) - } - partition2(predicate:(v:T)=>v is U): [Vector,Vector>]; ->partition2 : Symbol(Vector.partition2, Decl(conditionalTypes2.ts, 92, 5), Decl(conditionalTypes2.ts, 93, 88), Decl(conditionalTypes2.ts, 94, 64)) ->U : Symbol(U, Decl(conditionalTypes2.ts, 93, 15)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 89, 13)) ->predicate : Symbol(predicate, Decl(conditionalTypes2.ts, 93, 28)) ->v : Symbol(v, Decl(conditionalTypes2.ts, 93, 39)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 89, 13)) ->v : Symbol(v, Decl(conditionalTypes2.ts, 93, 39)) ->U : Symbol(U, Decl(conditionalTypes2.ts, 93, 15)) ->Vector : Symbol(Vector, Decl(conditionalTypes2.ts, 87, 1)) ->U : Symbol(U, Decl(conditionalTypes2.ts, 93, 15)) ->Vector : Symbol(Vector, Decl(conditionalTypes2.ts, 87, 1)) ->Exclude : Symbol(Exclude, Decl(lib.es5.d.ts, --, --)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 89, 13)) ->U : Symbol(U, Decl(conditionalTypes2.ts, 93, 15)) - - partition2(predicate:(x:T)=>boolean): [Vector,Vector]; ->partition2 : Symbol(Vector.partition2, Decl(conditionalTypes2.ts, 92, 5), Decl(conditionalTypes2.ts, 93, 88), Decl(conditionalTypes2.ts, 94, 64)) ->predicate : Symbol(predicate, Decl(conditionalTypes2.ts, 94, 15)) ->x : Symbol(x, Decl(conditionalTypes2.ts, 94, 26)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 89, 13)) ->Vector : Symbol(Vector, Decl(conditionalTypes2.ts, 87, 1)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 89, 13)) ->Vector : Symbol(Vector, Decl(conditionalTypes2.ts, 87, 1)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 89, 13)) - - partition2(predicate:(v:T)=>boolean): [Vector,Vector] { ->partition2 : Symbol(Vector.partition2, Decl(conditionalTypes2.ts, 92, 5), Decl(conditionalTypes2.ts, 93, 88), Decl(conditionalTypes2.ts, 94, 64)) ->U : Symbol(U, Decl(conditionalTypes2.ts, 95, 15)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 89, 13)) ->predicate : Symbol(predicate, Decl(conditionalTypes2.ts, 95, 28)) ->v : Symbol(v, Decl(conditionalTypes2.ts, 95, 39)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 89, 13)) ->Vector : Symbol(Vector, Decl(conditionalTypes2.ts, 87, 1)) ->U : Symbol(U, Decl(conditionalTypes2.ts, 95, 15)) ->Vector : Symbol(Vector, Decl(conditionalTypes2.ts, 87, 1)) - - return undefined; ->undefined : Symbol(undefined) - } -} - -interface A1 { ->A1 : Symbol(A1, Decl(conditionalTypes2.ts, 98, 1)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 100, 13)) - - bat: B1>; ->bat : Symbol(A1.bat, Decl(conditionalTypes2.ts, 100, 17)) ->B1 : Symbol(B1, Decl(conditionalTypes2.ts, 102, 1)) ->A1 : Symbol(A1, Decl(conditionalTypes2.ts, 98, 1)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 100, 13)) -} - -interface B1 extends A1 { ->B1 : Symbol(B1, Decl(conditionalTypes2.ts, 102, 1)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 104, 13)) ->A1 : Symbol(A1, Decl(conditionalTypes2.ts, 98, 1)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 104, 13)) - - bat: B1>; ->bat : Symbol(B1.bat, Decl(conditionalTypes2.ts, 104, 31)) ->B1 : Symbol(B1, Decl(conditionalTypes2.ts, 102, 1)) ->B1 : Symbol(B1, Decl(conditionalTypes2.ts, 102, 1)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 104, 13)) - - boom: T extends any ? true : true ->boom : Symbol(B1.boom, Decl(conditionalTypes2.ts, 105, 19)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 104, 13)) +>fooBat : Symbol(fooBat, Decl(conditionalTypes2.ts, 62, 63)) +>z : Symbol(z, Decl(conditionalTypes2.ts, 73, 75)) } // Repro from #22899 declare function toString1(value: object | Function): string ; ->toString1 : Symbol(toString1, Decl(conditionalTypes2.ts, 107, 1)) ->value : Symbol(value, Decl(conditionalTypes2.ts, 111, 27)) +>toString1 : Symbol(toString1, Decl(conditionalTypes2.ts, 77, 1)) +>value : Symbol(value, Decl(conditionalTypes2.ts, 81, 27)) >Function : Symbol(Function, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) declare function toString2(value: Function): string ; ->toString2 : Symbol(toString2, Decl(conditionalTypes2.ts, 111, 62)) ->value : Symbol(value, Decl(conditionalTypes2.ts, 112, 27)) +>toString2 : Symbol(toString2, Decl(conditionalTypes2.ts, 81, 62)) +>value : Symbol(value, Decl(conditionalTypes2.ts, 82, 27)) >Function : Symbol(Function, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) function foo(value: T) { ->foo : Symbol(foo, Decl(conditionalTypes2.ts, 112, 53)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 114, 13)) ->value : Symbol(value, Decl(conditionalTypes2.ts, 114, 16)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 114, 13)) +>foo : Symbol(foo, Decl(conditionalTypes2.ts, 82, 53)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 84, 13)) +>value : Symbol(value, Decl(conditionalTypes2.ts, 84, 16)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 84, 13)) if (isFunction(value)) { ->isFunction : Symbol(isFunction, Decl(conditionalTypes2.ts, 25, 1)) ->value : Symbol(value, Decl(conditionalTypes2.ts, 114, 16)) +>isFunction : Symbol(isFunction, Decl(conditionalTypes2.ts, 27, 1)) +>value : Symbol(value, Decl(conditionalTypes2.ts, 84, 16)) toString1(value); ->toString1 : Symbol(toString1, Decl(conditionalTypes2.ts, 107, 1)) ->value : Symbol(value, Decl(conditionalTypes2.ts, 114, 16)) +>toString1 : Symbol(toString1, Decl(conditionalTypes2.ts, 77, 1)) +>value : Symbol(value, Decl(conditionalTypes2.ts, 84, 16)) toString2(value); ->toString2 : Symbol(toString2, Decl(conditionalTypes2.ts, 111, 62)) ->value : Symbol(value, Decl(conditionalTypes2.ts, 114, 16)) +>toString2 : Symbol(toString2, Decl(conditionalTypes2.ts, 81, 62)) +>value : Symbol(value, Decl(conditionalTypes2.ts, 84, 16)) } } // Repro from #23052 type A = ->A : Symbol(A, Decl(conditionalTypes2.ts, 119, 1)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 123, 7)) ->V : Symbol(V, Decl(conditionalTypes2.ts, 123, 9)) ->E : Symbol(E, Decl(conditionalTypes2.ts, 123, 12)) +>A : Symbol(A, Decl(conditionalTypes2.ts, 89, 1)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 93, 7)) +>V : Symbol(V, Decl(conditionalTypes2.ts, 93, 9)) +>E : Symbol(E, Decl(conditionalTypes2.ts, 93, 12)) T extends object ->T : Symbol(T, Decl(conditionalTypes2.ts, 123, 7)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 93, 7)) ? { [Q in { [P in keyof T]: T[P] extends V ? P : P; }[keyof T]]: A; } ->Q : Symbol(Q, Decl(conditionalTypes2.ts, 125, 9)) ->P : Symbol(P, Decl(conditionalTypes2.ts, 125, 17)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 123, 7)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 123, 7)) ->P : Symbol(P, Decl(conditionalTypes2.ts, 125, 17)) ->V : Symbol(V, Decl(conditionalTypes2.ts, 123, 9)) ->P : Symbol(P, Decl(conditionalTypes2.ts, 125, 17)) ->P : Symbol(P, Decl(conditionalTypes2.ts, 125, 17)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 123, 7)) ->A : Symbol(A, Decl(conditionalTypes2.ts, 119, 1)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 123, 7)) ->Q : Symbol(Q, Decl(conditionalTypes2.ts, 125, 9)) ->V : Symbol(V, Decl(conditionalTypes2.ts, 123, 9)) ->E : Symbol(E, Decl(conditionalTypes2.ts, 123, 12)) +>Q : Symbol(Q, Decl(conditionalTypes2.ts, 95, 9)) +>P : Symbol(P, Decl(conditionalTypes2.ts, 95, 17)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 93, 7)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 93, 7)) +>P : Symbol(P, Decl(conditionalTypes2.ts, 95, 17)) +>V : Symbol(V, Decl(conditionalTypes2.ts, 93, 9)) +>P : Symbol(P, Decl(conditionalTypes2.ts, 95, 17)) +>P : Symbol(P, Decl(conditionalTypes2.ts, 95, 17)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 93, 7)) +>A : Symbol(A, Decl(conditionalTypes2.ts, 89, 1)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 93, 7)) +>Q : Symbol(Q, Decl(conditionalTypes2.ts, 95, 9)) +>V : Symbol(V, Decl(conditionalTypes2.ts, 93, 9)) +>E : Symbol(E, Decl(conditionalTypes2.ts, 93, 12)) : T extends V ? T : never; ->T : Symbol(T, Decl(conditionalTypes2.ts, 123, 7)) ->V : Symbol(V, Decl(conditionalTypes2.ts, 123, 9)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 123, 7)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 93, 7)) +>V : Symbol(V, Decl(conditionalTypes2.ts, 93, 9)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 93, 7)) type B = ->B : Symbol(B, Decl(conditionalTypes2.ts, 126, 30)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 128, 7)) ->V : Symbol(V, Decl(conditionalTypes2.ts, 128, 9)) +>B : Symbol(B, Decl(conditionalTypes2.ts, 96, 30)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 98, 7)) +>V : Symbol(V, Decl(conditionalTypes2.ts, 98, 9)) T extends object ->T : Symbol(T, Decl(conditionalTypes2.ts, 128, 7)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 98, 7)) ? { [Q in { [P in keyof T]: T[P] extends V ? P : P; }[keyof T]]: B; } ->Q : Symbol(Q, Decl(conditionalTypes2.ts, 130, 9)) ->P : Symbol(P, Decl(conditionalTypes2.ts, 130, 17)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 128, 7)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 128, 7)) ->P : Symbol(P, Decl(conditionalTypes2.ts, 130, 17)) ->V : Symbol(V, Decl(conditionalTypes2.ts, 128, 9)) ->P : Symbol(P, Decl(conditionalTypes2.ts, 130, 17)) ->P : Symbol(P, Decl(conditionalTypes2.ts, 130, 17)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 128, 7)) ->B : Symbol(B, Decl(conditionalTypes2.ts, 126, 30)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 128, 7)) ->Q : Symbol(Q, Decl(conditionalTypes2.ts, 130, 9)) ->V : Symbol(V, Decl(conditionalTypes2.ts, 128, 9)) +>Q : Symbol(Q, Decl(conditionalTypes2.ts, 100, 9)) +>P : Symbol(P, Decl(conditionalTypes2.ts, 100, 17)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 98, 7)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 98, 7)) +>P : Symbol(P, Decl(conditionalTypes2.ts, 100, 17)) +>V : Symbol(V, Decl(conditionalTypes2.ts, 98, 9)) +>P : Symbol(P, Decl(conditionalTypes2.ts, 100, 17)) +>P : Symbol(P, Decl(conditionalTypes2.ts, 100, 17)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 98, 7)) +>B : Symbol(B, Decl(conditionalTypes2.ts, 96, 30)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 98, 7)) +>Q : Symbol(Q, Decl(conditionalTypes2.ts, 100, 9)) +>V : Symbol(V, Decl(conditionalTypes2.ts, 98, 9)) : T extends V ? T : never; ->T : Symbol(T, Decl(conditionalTypes2.ts, 128, 7)) ->V : Symbol(V, Decl(conditionalTypes2.ts, 128, 9)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 128, 7)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 98, 7)) +>V : Symbol(V, Decl(conditionalTypes2.ts, 98, 9)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 98, 7)) type C = ->C : Symbol(C, Decl(conditionalTypes2.ts, 131, 30)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 133, 7)) ->V : Symbol(V, Decl(conditionalTypes2.ts, 133, 9)) ->E : Symbol(E, Decl(conditionalTypes2.ts, 133, 12)) +>C : Symbol(C, Decl(conditionalTypes2.ts, 101, 30)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 103, 7)) +>V : Symbol(V, Decl(conditionalTypes2.ts, 103, 9)) +>E : Symbol(E, Decl(conditionalTypes2.ts, 103, 12)) { [Q in { [P in keyof T]: T[P] extends V ? P : P; }[keyof T]]: C; }; ->Q : Symbol(Q, Decl(conditionalTypes2.ts, 134, 5)) ->P : Symbol(P, Decl(conditionalTypes2.ts, 134, 13)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 133, 7)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 133, 7)) ->P : Symbol(P, Decl(conditionalTypes2.ts, 134, 13)) ->V : Symbol(V, Decl(conditionalTypes2.ts, 133, 9)) ->P : Symbol(P, Decl(conditionalTypes2.ts, 134, 13)) ->P : Symbol(P, Decl(conditionalTypes2.ts, 134, 13)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 133, 7)) ->C : Symbol(C, Decl(conditionalTypes2.ts, 131, 30)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 133, 7)) ->Q : Symbol(Q, Decl(conditionalTypes2.ts, 134, 5)) ->V : Symbol(V, Decl(conditionalTypes2.ts, 133, 9)) ->E : Symbol(E, Decl(conditionalTypes2.ts, 133, 12)) +>Q : Symbol(Q, Decl(conditionalTypes2.ts, 104, 5)) +>P : Symbol(P, Decl(conditionalTypes2.ts, 104, 13)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 103, 7)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 103, 7)) +>P : Symbol(P, Decl(conditionalTypes2.ts, 104, 13)) +>V : Symbol(V, Decl(conditionalTypes2.ts, 103, 9)) +>P : Symbol(P, Decl(conditionalTypes2.ts, 104, 13)) +>P : Symbol(P, Decl(conditionalTypes2.ts, 104, 13)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 103, 7)) +>C : Symbol(C, Decl(conditionalTypes2.ts, 101, 30)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 103, 7)) +>Q : Symbol(Q, Decl(conditionalTypes2.ts, 104, 5)) +>V : Symbol(V, Decl(conditionalTypes2.ts, 103, 9)) +>E : Symbol(E, Decl(conditionalTypes2.ts, 103, 12)) // Repro from #23100 type A2 = ->A2 : Symbol(A2, Decl(conditionalTypes2.ts, 134, 82)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 138, 8)) ->V : Symbol(V, Decl(conditionalTypes2.ts, 138, 10)) ->E : Symbol(E, Decl(conditionalTypes2.ts, 138, 13)) +>A2 : Symbol(A2, Decl(conditionalTypes2.ts, 104, 82)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 108, 8)) +>V : Symbol(V, Decl(conditionalTypes2.ts, 108, 10)) +>E : Symbol(E, Decl(conditionalTypes2.ts, 108, 13)) T extends object ? T extends any[] ? T : { [Q in keyof T]: A2; } : T; ->T : Symbol(T, Decl(conditionalTypes2.ts, 138, 8)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 138, 8)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 138, 8)) ->Q : Symbol(Q, Decl(conditionalTypes2.ts, 139, 48)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 138, 8)) ->A2 : Symbol(A2, Decl(conditionalTypes2.ts, 134, 82)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 138, 8)) ->Q : Symbol(Q, Decl(conditionalTypes2.ts, 139, 48)) ->V : Symbol(V, Decl(conditionalTypes2.ts, 138, 10)) ->E : Symbol(E, Decl(conditionalTypes2.ts, 138, 13)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 138, 8)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 108, 8)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 108, 8)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 108, 8)) +>Q : Symbol(Q, Decl(conditionalTypes2.ts, 109, 48)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 108, 8)) +>A2 : Symbol(A2, Decl(conditionalTypes2.ts, 104, 82)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 108, 8)) +>Q : Symbol(Q, Decl(conditionalTypes2.ts, 109, 48)) +>V : Symbol(V, Decl(conditionalTypes2.ts, 108, 10)) +>E : Symbol(E, Decl(conditionalTypes2.ts, 108, 13)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 108, 8)) type B2 = ->B2 : Symbol(B2, Decl(conditionalTypes2.ts, 139, 85)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 141, 8)) ->V : Symbol(V, Decl(conditionalTypes2.ts, 141, 10)) +>B2 : Symbol(B2, Decl(conditionalTypes2.ts, 109, 85)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 111, 8)) +>V : Symbol(V, Decl(conditionalTypes2.ts, 111, 10)) T extends object ? T extends any[] ? T : { [Q in keyof T]: B2; } : T; ->T : Symbol(T, Decl(conditionalTypes2.ts, 141, 8)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 141, 8)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 141, 8)) ->Q : Symbol(Q, Decl(conditionalTypes2.ts, 142, 48)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 141, 8)) ->B2 : Symbol(B2, Decl(conditionalTypes2.ts, 139, 85)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 141, 8)) ->Q : Symbol(Q, Decl(conditionalTypes2.ts, 142, 48)) ->V : Symbol(V, Decl(conditionalTypes2.ts, 141, 10)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 141, 8)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 111, 8)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 111, 8)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 111, 8)) +>Q : Symbol(Q, Decl(conditionalTypes2.ts, 112, 48)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 111, 8)) +>B2 : Symbol(B2, Decl(conditionalTypes2.ts, 109, 85)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 111, 8)) +>Q : Symbol(Q, Decl(conditionalTypes2.ts, 112, 48)) +>V : Symbol(V, Decl(conditionalTypes2.ts, 111, 10)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 111, 8)) type C2 = ->C2 : Symbol(C2, Decl(conditionalTypes2.ts, 142, 82)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 144, 8)) ->V : Symbol(V, Decl(conditionalTypes2.ts, 144, 10)) ->E : Symbol(E, Decl(conditionalTypes2.ts, 144, 13)) +>C2 : Symbol(C2, Decl(conditionalTypes2.ts, 112, 82)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 114, 8)) +>V : Symbol(V, Decl(conditionalTypes2.ts, 114, 10)) +>E : Symbol(E, Decl(conditionalTypes2.ts, 114, 13)) T extends object ? { [Q in keyof T]: C2; } : T; ->T : Symbol(T, Decl(conditionalTypes2.ts, 144, 8)) ->Q : Symbol(Q, Decl(conditionalTypes2.ts, 145, 26)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 144, 8)) ->C2 : Symbol(C2, Decl(conditionalTypes2.ts, 142, 82)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 144, 8)) ->Q : Symbol(Q, Decl(conditionalTypes2.ts, 145, 26)) ->V : Symbol(V, Decl(conditionalTypes2.ts, 144, 10)) ->E : Symbol(E, Decl(conditionalTypes2.ts, 144, 13)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 144, 8)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 114, 8)) +>Q : Symbol(Q, Decl(conditionalTypes2.ts, 115, 26)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 114, 8)) +>C2 : Symbol(C2, Decl(conditionalTypes2.ts, 112, 82)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 114, 8)) +>Q : Symbol(Q, Decl(conditionalTypes2.ts, 115, 26)) +>V : Symbol(V, Decl(conditionalTypes2.ts, 114, 10)) +>E : Symbol(E, Decl(conditionalTypes2.ts, 114, 13)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 114, 8)) // Repro from #28654 type MaybeTrue = true extends T["b"] ? "yes" : "no"; ->MaybeTrue : Symbol(MaybeTrue, Decl(conditionalTypes2.ts, 145, 63)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 149, 15)) ->b : Symbol(b, Decl(conditionalTypes2.ts, 149, 26)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 149, 15)) +>MaybeTrue : Symbol(MaybeTrue, Decl(conditionalTypes2.ts, 115, 63)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 119, 15)) +>b : Symbol(b, Decl(conditionalTypes2.ts, 119, 26)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 119, 15)) type T0 = MaybeTrue<{ b: never }> // "no" ->T0 : Symbol(T0, Decl(conditionalTypes2.ts, 149, 78)) ->MaybeTrue : Symbol(MaybeTrue, Decl(conditionalTypes2.ts, 145, 63)) ->b : Symbol(b, Decl(conditionalTypes2.ts, 151, 21)) +>T0 : Symbol(T0, Decl(conditionalTypes2.ts, 119, 78)) +>MaybeTrue : Symbol(MaybeTrue, Decl(conditionalTypes2.ts, 115, 63)) +>b : Symbol(b, Decl(conditionalTypes2.ts, 121, 21)) type T1 = MaybeTrue<{ b: false }>; // "no" ->T1 : Symbol(T1, Decl(conditionalTypes2.ts, 151, 33)) ->MaybeTrue : Symbol(MaybeTrue, Decl(conditionalTypes2.ts, 145, 63)) ->b : Symbol(b, Decl(conditionalTypes2.ts, 152, 21)) +>T1 : Symbol(T1, Decl(conditionalTypes2.ts, 121, 33)) +>MaybeTrue : Symbol(MaybeTrue, Decl(conditionalTypes2.ts, 115, 63)) +>b : Symbol(b, Decl(conditionalTypes2.ts, 122, 21)) type T2 = MaybeTrue<{ b: true }>; // "yes" ->T2 : Symbol(T2, Decl(conditionalTypes2.ts, 152, 34)) ->MaybeTrue : Symbol(MaybeTrue, Decl(conditionalTypes2.ts, 145, 63)) ->b : Symbol(b, Decl(conditionalTypes2.ts, 153, 21)) +>T2 : Symbol(T2, Decl(conditionalTypes2.ts, 122, 34)) +>MaybeTrue : Symbol(MaybeTrue, Decl(conditionalTypes2.ts, 115, 63)) +>b : Symbol(b, Decl(conditionalTypes2.ts, 123, 21)) type T3 = MaybeTrue<{ b: boolean }>; // "yes" ->T3 : Symbol(T3, Decl(conditionalTypes2.ts, 153, 33)) ->MaybeTrue : Symbol(MaybeTrue, Decl(conditionalTypes2.ts, 145, 63)) ->b : Symbol(b, Decl(conditionalTypes2.ts, 154, 21)) +>T3 : Symbol(T3, Decl(conditionalTypes2.ts, 123, 33)) +>MaybeTrue : Symbol(MaybeTrue, Decl(conditionalTypes2.ts, 115, 63)) +>b : Symbol(b, Decl(conditionalTypes2.ts, 124, 21)) // Repro from #28824 type Union = 'a' | 'b'; ->Union : Symbol(Union, Decl(conditionalTypes2.ts, 154, 36)) +>Union : Symbol(Union, Decl(conditionalTypes2.ts, 124, 36)) type Product = { f1: A, f2: B}; ->Product : Symbol(Product, Decl(conditionalTypes2.ts, 158, 23)) ->A : Symbol(A, Decl(conditionalTypes2.ts, 159, 13)) ->Union : Symbol(Union, Decl(conditionalTypes2.ts, 154, 36)) ->B : Symbol(B, Decl(conditionalTypes2.ts, 159, 29)) ->f1 : Symbol(f1, Decl(conditionalTypes2.ts, 159, 36)) ->A : Symbol(A, Decl(conditionalTypes2.ts, 159, 13)) ->f2 : Symbol(f2, Decl(conditionalTypes2.ts, 159, 43)) ->B : Symbol(B, Decl(conditionalTypes2.ts, 159, 29)) +>Product : Symbol(Product, Decl(conditionalTypes2.ts, 128, 23)) +>A : Symbol(A, Decl(conditionalTypes2.ts, 129, 13)) +>Union : Symbol(Union, Decl(conditionalTypes2.ts, 124, 36)) +>B : Symbol(B, Decl(conditionalTypes2.ts, 129, 29)) +>f1 : Symbol(f1, Decl(conditionalTypes2.ts, 129, 36)) +>A : Symbol(A, Decl(conditionalTypes2.ts, 129, 13)) +>f2 : Symbol(f2, Decl(conditionalTypes2.ts, 129, 43)) +>B : Symbol(B, Decl(conditionalTypes2.ts, 129, 29)) type ProductUnion = Product<'a', 0> | Product<'b', 1>; ->ProductUnion : Symbol(ProductUnion, Decl(conditionalTypes2.ts, 159, 51)) ->Product : Symbol(Product, Decl(conditionalTypes2.ts, 158, 23)) ->Product : Symbol(Product, Decl(conditionalTypes2.ts, 158, 23)) +>ProductUnion : Symbol(ProductUnion, Decl(conditionalTypes2.ts, 129, 51)) +>Product : Symbol(Product, Decl(conditionalTypes2.ts, 128, 23)) +>Product : Symbol(Product, Decl(conditionalTypes2.ts, 128, 23)) // {a: "b"; b: "a"} type UnionComplement = { ->UnionComplement : Symbol(UnionComplement, Decl(conditionalTypes2.ts, 160, 54)) +>UnionComplement : Symbol(UnionComplement, Decl(conditionalTypes2.ts, 130, 54)) [K in Union]: Exclude ->K : Symbol(K, Decl(conditionalTypes2.ts, 164, 3)) ->Union : Symbol(Union, Decl(conditionalTypes2.ts, 154, 36)) +>K : Symbol(K, Decl(conditionalTypes2.ts, 134, 3)) +>Union : Symbol(Union, Decl(conditionalTypes2.ts, 124, 36)) >Exclude : Symbol(Exclude, Decl(lib.es5.d.ts, --, --)) ->Union : Symbol(Union, Decl(conditionalTypes2.ts, 154, 36)) ->K : Symbol(K, Decl(conditionalTypes2.ts, 164, 3)) +>Union : Symbol(Union, Decl(conditionalTypes2.ts, 124, 36)) +>K : Symbol(K, Decl(conditionalTypes2.ts, 134, 3)) }; type UCA = UnionComplement['a']; ->UCA : Symbol(UCA, Decl(conditionalTypes2.ts, 165, 2)) ->UnionComplement : Symbol(UnionComplement, Decl(conditionalTypes2.ts, 160, 54)) +>UCA : Symbol(UCA, Decl(conditionalTypes2.ts, 135, 2)) +>UnionComplement : Symbol(UnionComplement, Decl(conditionalTypes2.ts, 130, 54)) type UCB = UnionComplement['b']; ->UCB : Symbol(UCB, Decl(conditionalTypes2.ts, 166, 32)) ->UnionComplement : Symbol(UnionComplement, Decl(conditionalTypes2.ts, 160, 54)) +>UCB : Symbol(UCB, Decl(conditionalTypes2.ts, 136, 32)) +>UnionComplement : Symbol(UnionComplement, Decl(conditionalTypes2.ts, 130, 54)) // {a: "a"; b: "b"} type UnionComplementComplement = { ->UnionComplementComplement : Symbol(UnionComplementComplement, Decl(conditionalTypes2.ts, 167, 32)) +>UnionComplementComplement : Symbol(UnionComplementComplement, Decl(conditionalTypes2.ts, 137, 32)) [K in Union]: Exclude> ->K : Symbol(K, Decl(conditionalTypes2.ts, 171, 3)) ->Union : Symbol(Union, Decl(conditionalTypes2.ts, 154, 36)) +>K : Symbol(K, Decl(conditionalTypes2.ts, 141, 3)) +>Union : Symbol(Union, Decl(conditionalTypes2.ts, 124, 36)) >Exclude : Symbol(Exclude, Decl(lib.es5.d.ts, --, --)) ->Union : Symbol(Union, Decl(conditionalTypes2.ts, 154, 36)) +>Union : Symbol(Union, Decl(conditionalTypes2.ts, 124, 36)) >Exclude : Symbol(Exclude, Decl(lib.es5.d.ts, --, --)) ->Union : Symbol(Union, Decl(conditionalTypes2.ts, 154, 36)) ->K : Symbol(K, Decl(conditionalTypes2.ts, 171, 3)) +>Union : Symbol(Union, Decl(conditionalTypes2.ts, 124, 36)) +>K : Symbol(K, Decl(conditionalTypes2.ts, 141, 3)) }; type UCCA = UnionComplementComplement['a']; ->UCCA : Symbol(UCCA, Decl(conditionalTypes2.ts, 172, 2)) ->UnionComplementComplement : Symbol(UnionComplementComplement, Decl(conditionalTypes2.ts, 167, 32)) +>UCCA : Symbol(UCCA, Decl(conditionalTypes2.ts, 142, 2)) +>UnionComplementComplement : Symbol(UnionComplementComplement, Decl(conditionalTypes2.ts, 137, 32)) type UCCB = UnionComplementComplement['b']; ->UCCB : Symbol(UCCB, Decl(conditionalTypes2.ts, 173, 43)) ->UnionComplementComplement : Symbol(UnionComplementComplement, Decl(conditionalTypes2.ts, 167, 32)) +>UCCB : Symbol(UCCB, Decl(conditionalTypes2.ts, 143, 43)) +>UnionComplementComplement : Symbol(UnionComplementComplement, Decl(conditionalTypes2.ts, 137, 32)) // {a: Product<'b', 1>; b: Product<'a', 0>} type ProductComplement = { ->ProductComplement : Symbol(ProductComplement, Decl(conditionalTypes2.ts, 174, 43)) +>ProductComplement : Symbol(ProductComplement, Decl(conditionalTypes2.ts, 144, 43)) [K in Union]: Exclude ->K : Symbol(K, Decl(conditionalTypes2.ts, 178, 3)) ->Union : Symbol(Union, Decl(conditionalTypes2.ts, 154, 36)) +>K : Symbol(K, Decl(conditionalTypes2.ts, 148, 3)) +>Union : Symbol(Union, Decl(conditionalTypes2.ts, 124, 36)) >Exclude : Symbol(Exclude, Decl(lib.es5.d.ts, --, --)) ->ProductUnion : Symbol(ProductUnion, Decl(conditionalTypes2.ts, 159, 51)) ->f1 : Symbol(f1, Decl(conditionalTypes2.ts, 178, 39)) ->K : Symbol(K, Decl(conditionalTypes2.ts, 178, 3)) +>ProductUnion : Symbol(ProductUnion, Decl(conditionalTypes2.ts, 129, 51)) +>f1 : Symbol(f1, Decl(conditionalTypes2.ts, 148, 39)) +>K : Symbol(K, Decl(conditionalTypes2.ts, 148, 3)) }; type PCA = ProductComplement['a']; ->PCA : Symbol(PCA, Decl(conditionalTypes2.ts, 179, 2)) ->ProductComplement : Symbol(ProductComplement, Decl(conditionalTypes2.ts, 174, 43)) +>PCA : Symbol(PCA, Decl(conditionalTypes2.ts, 149, 2)) +>ProductComplement : Symbol(ProductComplement, Decl(conditionalTypes2.ts, 144, 43)) type PCB = ProductComplement['b']; ->PCB : Symbol(PCB, Decl(conditionalTypes2.ts, 180, 34)) ->ProductComplement : Symbol(ProductComplement, Decl(conditionalTypes2.ts, 174, 43)) +>PCB : Symbol(PCB, Decl(conditionalTypes2.ts, 150, 34)) +>ProductComplement : Symbol(ProductComplement, Decl(conditionalTypes2.ts, 144, 43)) // {a: Product<'a', 0>; b: Product<'b', 1>} type ProductComplementComplement = { ->ProductComplementComplement : Symbol(ProductComplementComplement, Decl(conditionalTypes2.ts, 181, 34)) +>ProductComplementComplement : Symbol(ProductComplementComplement, Decl(conditionalTypes2.ts, 151, 34)) [K in Union]: Exclude> ->K : Symbol(K, Decl(conditionalTypes2.ts, 185, 3)) ->Union : Symbol(Union, Decl(conditionalTypes2.ts, 154, 36)) +>K : Symbol(K, Decl(conditionalTypes2.ts, 155, 3)) +>Union : Symbol(Union, Decl(conditionalTypes2.ts, 124, 36)) >Exclude : Symbol(Exclude, Decl(lib.es5.d.ts, --, --)) ->ProductUnion : Symbol(ProductUnion, Decl(conditionalTypes2.ts, 159, 51)) +>ProductUnion : Symbol(ProductUnion, Decl(conditionalTypes2.ts, 129, 51)) >Exclude : Symbol(Exclude, Decl(lib.es5.d.ts, --, --)) ->ProductUnion : Symbol(ProductUnion, Decl(conditionalTypes2.ts, 159, 51)) ->f1 : Symbol(f1, Decl(conditionalTypes2.ts, 185, 61)) ->K : Symbol(K, Decl(conditionalTypes2.ts, 185, 3)) +>ProductUnion : Symbol(ProductUnion, Decl(conditionalTypes2.ts, 129, 51)) +>f1 : Symbol(f1, Decl(conditionalTypes2.ts, 155, 61)) +>K : Symbol(K, Decl(conditionalTypes2.ts, 155, 3)) }; type PCCA = ProductComplementComplement['a']; ->PCCA : Symbol(PCCA, Decl(conditionalTypes2.ts, 186, 2)) ->ProductComplementComplement : Symbol(ProductComplementComplement, Decl(conditionalTypes2.ts, 181, 34)) +>PCCA : Symbol(PCCA, Decl(conditionalTypes2.ts, 156, 2)) +>ProductComplementComplement : Symbol(ProductComplementComplement, Decl(conditionalTypes2.ts, 151, 34)) type PCCB = ProductComplementComplement['b']; ->PCCB : Symbol(PCCB, Decl(conditionalTypes2.ts, 187, 45)) ->ProductComplementComplement : Symbol(ProductComplementComplement, Decl(conditionalTypes2.ts, 181, 34)) +>PCCB : Symbol(PCCB, Decl(conditionalTypes2.ts, 157, 45)) +>ProductComplementComplement : Symbol(ProductComplementComplement, Decl(conditionalTypes2.ts, 151, 34)) + +// Repros from #27118 + +type MyElement = [A] extends [[infer E]] ? E : never; +>MyElement : Symbol(MyElement, Decl(conditionalTypes2.ts, 158, 45)) +>A : Symbol(A, Decl(conditionalTypes2.ts, 162, 15)) +>A : Symbol(A, Decl(conditionalTypes2.ts, 162, 15)) +>E : Symbol(E, Decl(conditionalTypes2.ts, 162, 39)) +>E : Symbol(E, Decl(conditionalTypes2.ts, 162, 39)) + +function oops(arg: MyElement): MyElement { +>oops : Symbol(oops, Decl(conditionalTypes2.ts, 162, 56)) +>A : Symbol(A, Decl(conditionalTypes2.ts, 163, 14)) +>B : Symbol(B, Decl(conditionalTypes2.ts, 163, 16)) +>A : Symbol(A, Decl(conditionalTypes2.ts, 163, 14)) +>arg : Symbol(arg, Decl(conditionalTypes2.ts, 163, 30)) +>MyElement : Symbol(MyElement, Decl(conditionalTypes2.ts, 158, 45)) +>A : Symbol(A, Decl(conditionalTypes2.ts, 163, 14)) +>MyElement : Symbol(MyElement, Decl(conditionalTypes2.ts, 158, 45)) +>B : Symbol(B, Decl(conditionalTypes2.ts, 163, 16)) + + return arg; // Unsound, should be error +>arg : Symbol(arg, Decl(conditionalTypes2.ts, 163, 30)) +} + +type MyAcceptor = [A] extends [[infer E]] ? (arg: E) => void : never; +>MyAcceptor : Symbol(MyAcceptor, Decl(conditionalTypes2.ts, 165, 1)) +>A : Symbol(A, Decl(conditionalTypes2.ts, 167, 16)) +>A : Symbol(A, Decl(conditionalTypes2.ts, 167, 16)) +>E : Symbol(E, Decl(conditionalTypes2.ts, 167, 40)) +>arg : Symbol(arg, Decl(conditionalTypes2.ts, 167, 48)) +>E : Symbol(E, Decl(conditionalTypes2.ts, 167, 40)) + +function oops2(arg: MyAcceptor): MyAcceptor { +>oops2 : Symbol(oops2, Decl(conditionalTypes2.ts, 167, 72)) +>A : Symbol(A, Decl(conditionalTypes2.ts, 168, 15)) +>B : Symbol(B, Decl(conditionalTypes2.ts, 168, 17)) +>A : Symbol(A, Decl(conditionalTypes2.ts, 168, 15)) +>arg : Symbol(arg, Decl(conditionalTypes2.ts, 168, 31)) +>MyAcceptor : Symbol(MyAcceptor, Decl(conditionalTypes2.ts, 165, 1)) +>B : Symbol(B, Decl(conditionalTypes2.ts, 168, 17)) +>MyAcceptor : Symbol(MyAcceptor, Decl(conditionalTypes2.ts, 165, 1)) +>A : Symbol(A, Decl(conditionalTypes2.ts, 168, 15)) + + return arg; // Unsound, should be error +>arg : Symbol(arg, Decl(conditionalTypes2.ts, 168, 31)) +} + +type Dist = T extends number ? number : string; +>Dist : Symbol(Dist, Decl(conditionalTypes2.ts, 170, 1)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 172, 10)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 172, 10)) + +type Aux = A["a"] extends number ? number : string; +>Aux : Symbol(Aux, Decl(conditionalTypes2.ts, 172, 50)) +>A : Symbol(A, Decl(conditionalTypes2.ts, 173, 9)) +>a : Symbol(a, Decl(conditionalTypes2.ts, 173, 20)) +>A : Symbol(A, Decl(conditionalTypes2.ts, 173, 9)) + +type Nondist = Aux<{a: T}>; +>Nondist : Symbol(Nondist, Decl(conditionalTypes2.ts, 173, 77)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 174, 13)) +>Aux : Symbol(Aux, Decl(conditionalTypes2.ts, 172, 50)) +>a : Symbol(a, Decl(conditionalTypes2.ts, 174, 23)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 174, 13)) + +function oops3(arg: Dist): Nondist { +>oops3 : Symbol(oops3, Decl(conditionalTypes2.ts, 174, 30)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 175, 15)) +>arg : Symbol(arg, Decl(conditionalTypes2.ts, 175, 18)) +>Dist : Symbol(Dist, Decl(conditionalTypes2.ts, 170, 1)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 175, 15)) +>Nondist : Symbol(Nondist, Decl(conditionalTypes2.ts, 173, 77)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 175, 15)) + + return arg; // Unsound, should be error +>arg : Symbol(arg, Decl(conditionalTypes2.ts, 175, 18)) +} diff --git a/tests/baselines/reference/conditionalTypes2.types b/tests/baselines/reference/conditionalTypes2.types index aac6ba47475..3cffe6ab48e 100644 --- a/tests/baselines/reference/conditionalTypes2.types +++ b/tests/baselines/reference/conditionalTypes2.types @@ -1,4 +1,6 @@ === tests/cases/conformance/types/conditional/conditionalTypes2.ts === +// #27118: Conditional types are now invariant in the check type. + interface Covariant { foo: T extends string ? T : number; >foo : T extends string ? T : number @@ -19,7 +21,7 @@ function f1(a: Covariant, b: Covariant) { >a : Covariant >b : Covariant - a = b; + a = b; // Error >a = b : Covariant >a : Covariant >b : Covariant @@ -40,7 +42,7 @@ function f2(a: Contravariant, b: Contravariant) { >a : Contravariant >b : Contravariant - b = a; + b = a; // Error >b = a : Contravariant >b : Contravariant >a : Contravariant @@ -207,71 +209,6 @@ function f21(x: Extract, Bar>, y: Extract, z: E >z : Extract2 } -// Repros from #22860 - -class Opt { ->Opt : Opt - - toVector(): Vector { ->toVector : () => Vector - - return undefined; ->undefined : any ->undefined : undefined - } -} - -interface Seq { - tail(): Opt>; ->tail : () => Opt> -} - -class Vector implements Seq { ->Vector : Vector - - tail(): Opt> { ->tail : () => Opt> - - return undefined; ->undefined : any ->undefined : undefined - } - partition2(predicate:(v:T)=>v is U): [Vector,Vector>]; ->partition2 : { (predicate: (v: T) => v is U): [Vector, Vector>]; (predicate: (x: T) => boolean): [Vector, Vector]; } ->predicate : (v: T) => v is U ->v : T - - partition2(predicate:(x:T)=>boolean): [Vector,Vector]; ->partition2 : { (predicate: (v: T) => v is U): [Vector, Vector>]; (predicate: (x: T) => boolean): [Vector, Vector]; } ->predicate : (x: T) => boolean ->x : T - - partition2(predicate:(v:T)=>boolean): [Vector,Vector] { ->partition2 : { (predicate: (v: T) => v is U): [Vector, Vector>]; (predicate: (x: T) => boolean): [Vector, Vector]; } ->predicate : (v: T) => boolean ->v : T - - return undefined; ->undefined : any ->undefined : undefined - } -} - -interface A1 { - bat: B1>; ->bat : B1> -} - -interface B1 extends A1 { - bat: B1>; ->bat : B1> - - boom: T extends any ? true : true ->boom : T extends any ? true : true ->true : true ->true : true -} - // Repro from #22899 declare function toString1(value: object | Function): string ; @@ -431,3 +368,47 @@ type PCCA = ProductComplementComplement['a']; type PCCB = ProductComplementComplement['b']; >PCCB : Product<"b", 1> +// Repros from #27118 + +type MyElement = [A] extends [[infer E]] ? E : never; +>MyElement : MyElement + +function oops(arg: MyElement): MyElement { +>oops : (arg: MyElement) => MyElement +>arg : MyElement + + return arg; // Unsound, should be error +>arg : MyElement +} + +type MyAcceptor = [A] extends [[infer E]] ? (arg: E) => void : never; +>MyAcceptor : MyAcceptor +>arg : E + +function oops2(arg: MyAcceptor): MyAcceptor { +>oops2 : (arg: MyAcceptor) => MyAcceptor +>arg : MyAcceptor + + return arg; // Unsound, should be error +>arg : MyAcceptor +} + +type Dist = T extends number ? number : string; +>Dist : Dist + +type Aux = A["a"] extends number ? number : string; +>Aux : Aux +>a : unknown + +type Nondist = Aux<{a: T}>; +>Nondist : Aux<{ a: T; }> +>a : T + +function oops3(arg: Dist): Nondist { +>oops3 : (arg: Dist) => Aux<{ a: T; }> +>arg : Dist + + return arg; // Unsound, should be error +>arg : Dist +} + diff --git a/tests/cases/conformance/types/conditional/conditionalTypes2.ts b/tests/cases/conformance/types/conditional/conditionalTypes2.ts index 4b65b5ddeb2..5d73c58fe7f 100644 --- a/tests/cases/conformance/types/conditional/conditionalTypes2.ts +++ b/tests/cases/conformance/types/conditional/conditionalTypes2.ts @@ -1,6 +1,8 @@ // @strict: true // @declaration: true +// #27118: Conditional types are now invariant in the check type. + interface Covariant { foo: T extends string ? T : number; } @@ -14,13 +16,13 @@ interface Invariant { } function f1(a: Covariant, b: Covariant) { - a = b; + a = b; // Error b = a; // Error } function f2(a: Contravariant, b: Contravariant) { a = b; // Error - b = a; + b = a; // Error } function f3(a: Invariant, b: Invariant) { @@ -78,38 +80,6 @@ function f21(x: Extract, Bar>, y: Extract, z: E fooBat(z); // Error } -// Repros from #22860 - -class Opt { - toVector(): Vector { - return undefined; - } -} - -interface Seq { - tail(): Opt>; -} - -class Vector implements Seq { - tail(): Opt> { - return undefined; - } - partition2(predicate:(v:T)=>v is U): [Vector,Vector>]; - partition2(predicate:(x:T)=>boolean): [Vector,Vector]; - partition2(predicate:(v:T)=>boolean): [Vector,Vector] { - return undefined; - } -} - -interface A1 { - bat: B1>; -} - -interface B1 extends A1 { - bat: B1>; - boom: T extends any ? true : true -} - // Repro from #22899 declare function toString1(value: object | Function): string ; @@ -190,3 +160,22 @@ type ProductComplementComplement = { }; type PCCA = ProductComplementComplement['a']; type PCCB = ProductComplementComplement['b']; + +// Repros from #27118 + +type MyElement = [A] extends [[infer E]] ? E : never; +function oops(arg: MyElement): MyElement { + return arg; // Unsound, should be error +} + +type MyAcceptor = [A] extends [[infer E]] ? (arg: E) => void : never; +function oops2(arg: MyAcceptor): MyAcceptor { + return arg; // Unsound, should be error +} + +type Dist = T extends number ? number : string; +type Aux = A["a"] extends number ? number : string; +type Nondist = Aux<{a: T}>; +function oops3(arg: Dist): Nondist { + return arg; // Unsound, should be error +} From 9a0a838d1270d46212848ca0e7cafa435a65112d Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sun, 10 Feb 2019 07:48:22 -0800 Subject: [PATCH 037/149] Use getIndexedAccess to compute type for contextual rest parameters --- src/compiler/checker.ts | 21 ++++++++++----------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index f7cc72c534d..354d6af67be 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -21550,13 +21550,8 @@ namespace ts { } if (signature.hasRestParameter) { const restType = getTypeOfSymbol(signature.parameters[paramCount]); - if (isTupleType(restType)) { - if (pos - paramCount < getLengthOfTupleType(restType)) { - return restType.typeArguments![pos - paramCount]; - } - return getRestTypeOfTupleType(restType); - } - return getIndexTypeOfType(restType, IndexKind.Number); + const indexType = getLiteralType(pos - paramCount); + return getIndexedAccessType(restType, indexType); } return undefined; } @@ -21564,18 +21559,22 @@ namespace ts { function getRestTypeAtPosition(source: Signature, pos: number): Type { const paramCount = getParameterCount(source); const restType = getEffectiveRestType(source); - if (restType && pos === paramCount - 1) { + const nonRestCount = paramCount - (restType ? 1 : 0); + if (restType && pos === nonRestCount) { return restType; } - const start = restType ? Math.min(pos, paramCount - 1) : pos; const types = []; const names = []; - for (let i = start; i < paramCount; i++) { + for (let i = pos; i < nonRestCount; i++) { types.push(getTypeAtPosition(source, i)); names.push(getParameterNameAtPosition(source, i)); } + if (restType) { + types.push(getIndexedAccessType(restType, numberType)); + names.push(getParameterNameAtPosition(source, nonRestCount)); + } const minArgumentCount = getMinArgumentCount(source); - const minLength = minArgumentCount < start ? 0 : minArgumentCount - start; + const minLength = minArgumentCount < pos ? 0 : minArgumentCount - pos; return createTupleType(types, minLength, !!restType, /*readonly*/ false, names); } From 1f3213981181d6ff68e6f6e478032cb02d962961 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sun, 10 Feb 2019 15:07:01 -0800 Subject: [PATCH 038/149] Make inferences to union types containing multiple naked type variables --- src/compiler/checker.ts | 27 ++++++++------------------- 1 file changed, 8 insertions(+), 19 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index f7cc72c534d..9dc9efdf514 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -14472,26 +14472,15 @@ namespace ts { inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)])); } else if (target.flags & TypeFlags.UnionOrIntersection) { - const targetTypes = (target).types; - let typeVariableCount = 0; - let typeVariable: TypeParameter | IndexedAccessType | undefined; - // First infer to each type in union or intersection that isn't a type variable - for (const t of targetTypes) { - if (getInferenceInfoForType(t)) { - typeVariable = t; - typeVariableCount++; - } - else { - inferFromTypes(source, t); - } - } - // Next, if target containings a single naked type variable, make a secondary inference to that type - // variable. This gives meaningful results for union types in co-variant positions and intersection - // types in contra-variant positions (such as callback parameters). - if (typeVariableCount === 1) { + for (const t of (target).types) { const savePriority = priority; - priority |= InferencePriority.NakedTypeVariable; - inferFromTypes(source, typeVariable!); + // Inferences directly to naked type variables are given lower priority as they are + // less specific. For example, when inferring from Promise to T | Promise, + // we want to infer string for T, not Promise | string. + if (getInferenceInfoForType(t)) { + priority |= InferencePriority.NakedTypeVariable; + } + inferFromTypes(source, t); priority = savePriority; } } From 3ffb15fd7045c82393034ae4315ddd3633280db0 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sun, 10 Feb 2019 15:16:32 -0800 Subject: [PATCH 039/149] Accept new baselines --- .../conditionalTypeDoesntSpinForever.types | 16 ++++++++-------- tests/baselines/reference/objectSpread.types | 2 +- .../baselines/reference/restTupleElements1.types | 2 +- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/tests/baselines/reference/conditionalTypeDoesntSpinForever.types b/tests/baselines/reference/conditionalTypeDoesntSpinForever.types index d4fe4bf4826..1f4b4a62cd2 100644 --- a/tests/baselines/reference/conditionalTypeDoesntSpinForever.types +++ b/tests/baselines/reference/conditionalTypeDoesntSpinForever.types @@ -120,9 +120,9 @@ export enum PubSubRecordIsStoredInRedisAsA { buildPubSubRecordType(Object.assign({}, soFar, {storedAs: PubSubRecordIsStoredInRedisAsA.jsonEncodedRedisString})) as >buildPubSubRecordType(Object.assign({}, soFar, {storedAs: PubSubRecordIsStoredInRedisAsA.jsonEncodedRedisString})) as BuildPubSubRecordType : BuildPubSubRecordType ->buildPubSubRecordType(Object.assign({}, soFar, {storedAs: PubSubRecordIsStoredInRedisAsA.jsonEncodedRedisString})) : BuildPubSubRecordType +>buildPubSubRecordType(Object.assign({}, soFar, {storedAs: PubSubRecordIsStoredInRedisAsA.jsonEncodedRedisString})) : BuildPubSubRecordType >buildPubSubRecordType : (soFar: SO_FAR) => BuildPubSubRecordType ->Object.assign({}, soFar, {storedAs: PubSubRecordIsStoredInRedisAsA.jsonEncodedRedisString}) : SO_FAR & { storedAs: PubSubRecordIsStoredInRedisAsA; } +>Object.assign({}, soFar, {storedAs: PubSubRecordIsStoredInRedisAsA.jsonEncodedRedisString}) : SO_FAR & { storedAs: PubSubRecordIsStoredInRedisAsA.jsonEncodedRedisString; } >Object.assign : { (target: T, source: U): T & U; (target: T, source1: U, source2: V): T & U & V; (target: T, source1: U, source2: V, source3: W): T & U & V & W; (target: object, ...sources: any[]): any; } >Object : ObjectConstructor >assign : { (target: T, source: U): T & U; (target: T, source1: U, source2: V): T & U & V; (target: T, source1: U, source2: V, source3: W): T & U & V & W; (target: object, ...sources: any[]): any; } @@ -144,9 +144,9 @@ export enum PubSubRecordIsStoredInRedisAsA { buildPubSubRecordType(Object.assign({}, soFar, {storedAs: PubSubRecordIsStoredInRedisAsA.redisHash})) as >buildPubSubRecordType(Object.assign({}, soFar, {storedAs: PubSubRecordIsStoredInRedisAsA.redisHash})) as BuildPubSubRecordType : BuildPubSubRecordType ->buildPubSubRecordType(Object.assign({}, soFar, {storedAs: PubSubRecordIsStoredInRedisAsA.redisHash})) : BuildPubSubRecordType +>buildPubSubRecordType(Object.assign({}, soFar, {storedAs: PubSubRecordIsStoredInRedisAsA.redisHash})) : BuildPubSubRecordType >buildPubSubRecordType : (soFar: SO_FAR) => BuildPubSubRecordType ->Object.assign({}, soFar, {storedAs: PubSubRecordIsStoredInRedisAsA.redisHash}) : SO_FAR & { storedAs: PubSubRecordIsStoredInRedisAsA; } +>Object.assign({}, soFar, {storedAs: PubSubRecordIsStoredInRedisAsA.redisHash}) : SO_FAR & { storedAs: PubSubRecordIsStoredInRedisAsA.redisHash; } >Object.assign : { (target: T, source: U): T & U; (target: T, source1: U, source2: V): T & U & V; (target: T, source1: U, source2: V, source3: W): T & U & V & W; (target: object, ...sources: any[]): any; } >Object : ObjectConstructor >assign : { (target: T, source: U): T & U; (target: T, source1: U, source2: V): T & U & V; (target: T, source1: U, source2: V, source3: W): T & U & V & W; (target: object, ...sources: any[]): any; } @@ -337,16 +337,16 @@ export enum PubSubRecordIsStoredInRedisAsA { buildPubSubRecordType(Object.assign({}, soFar, {maxMsToWaitBeforePublishing: 0})) as BuildPubSubRecordType, >buildPubSubRecordType(Object.assign({}, soFar, {maxMsToWaitBeforePublishing: 0})) as BuildPubSubRecordType : BuildPubSubRecordType ->buildPubSubRecordType(Object.assign({}, soFar, {maxMsToWaitBeforePublishing: 0})) : BuildPubSubRecordType +>buildPubSubRecordType(Object.assign({}, soFar, {maxMsToWaitBeforePublishing: 0})) : BuildPubSubRecordType >buildPubSubRecordType : (soFar: SO_FAR) => BuildPubSubRecordType ->Object.assign({}, soFar, {maxMsToWaitBeforePublishing: 0}) : SO_FAR & { maxMsToWaitBeforePublishing: number; } +>Object.assign({}, soFar, {maxMsToWaitBeforePublishing: 0}) : SO_FAR & { maxMsToWaitBeforePublishing: 0; } >Object.assign : { (target: T, source: U): T & U; (target: T, source1: U, source2: V): T & U & V; (target: T, source1: U, source2: V, source3: W): T & U & V & W; (target: object, ...sources: any[]): any; } >Object : ObjectConstructor >assign : { (target: T, source: U): T & U; (target: T, source1: U, source2: V): T & U & V; (target: T, source1: U, source2: V, source3: W): T & U & V & W; (target: object, ...sources: any[]): any; } >{} : {} >soFar : SO_FAR ->{maxMsToWaitBeforePublishing: 0} : { maxMsToWaitBeforePublishing: number; } ->maxMsToWaitBeforePublishing : number +>{maxMsToWaitBeforePublishing: 0} : { maxMsToWaitBeforePublishing: 0; } +>maxMsToWaitBeforePublishing : 0 >0 : 0 >maxMsToWaitBeforePublishing : 0 } diff --git a/tests/baselines/reference/objectSpread.types b/tests/baselines/reference/objectSpread.types index 0ffd5dd20b7..e095a4e03bb 100644 --- a/tests/baselines/reference/objectSpread.types +++ b/tests/baselines/reference/objectSpread.types @@ -602,7 +602,7 @@ let exclusive: { id: string, a: number, b: string, c: string, d: boolean } = >d : boolean f({ a: 1, b: 'yes' }, { c: 'no', d: false }) ->f({ a: 1, b: 'yes' }, { c: 'no', d: false }) : { a: number; b: string; } & { c: string; d: boolean; } & { id: string; } +>f({ a: 1, b: 'yes' }, { c: 'no', d: false }) : { a: number; b: string; } & { c: string; d: false; } & { id: string; } >f : (t: T, u: U) => T & U & { id: string; } >{ a: 1, b: 'yes' } : { a: number; b: string; } >a : number diff --git a/tests/baselines/reference/restTupleElements1.types b/tests/baselines/reference/restTupleElements1.types index 9a8b3aaeb7e..ffa20bf503e 100644 --- a/tests/baselines/reference/restTupleElements1.types +++ b/tests/baselines/reference/restTupleElements1.types @@ -173,7 +173,7 @@ f0([]); // Error >[] : never[] f0([1]); ->f0([1]) : [number, {}] +>f0([1]) : [number, number] >f0 : (x: [T, ...U[]]) => [T, U] >[1] : [number] >1 : 1 From 15610faa9de4b06ecc24eec6f3c83948b4dd77cd Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sun, 10 Feb 2019 15:18:45 -0800 Subject: [PATCH 040/149] Update test --- tests/cases/compiler/jqueryInference.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/cases/compiler/jqueryInference.ts b/tests/cases/compiler/jqueryInference.ts index 60165916257..5784638e453 100644 --- a/tests/cases/compiler/jqueryInference.ts +++ b/tests/cases/compiler/jqueryInference.ts @@ -10,4 +10,4 @@ declare function shouldBeIdentity(p: DoNothingAlias): MyPromise; var p2 = shouldBeIdentity(p1); -var p2: MyPromise; +var p2: MyPromise; From 62e270c04d014d58d5bde60d026d91ea5e022c3e Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sun, 10 Feb 2019 15:18:51 -0800 Subject: [PATCH 041/149] Accept new baselines --- tests/baselines/reference/jqueryInference.js | 2 +- tests/baselines/reference/jqueryInference.symbols | 2 +- tests/baselines/reference/jqueryInference.types | 8 ++++---- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/tests/baselines/reference/jqueryInference.js b/tests/baselines/reference/jqueryInference.js index 05664a889de..cea70bc4391 100644 --- a/tests/baselines/reference/jqueryInference.js +++ b/tests/baselines/reference/jqueryInference.js @@ -11,7 +11,7 @@ declare function shouldBeIdentity(p: DoNothingAlias): MyPromise; var p2 = shouldBeIdentity(p1); -var p2: MyPromise; +var p2: MyPromise; //// [jqueryInference.js] diff --git a/tests/baselines/reference/jqueryInference.symbols b/tests/baselines/reference/jqueryInference.symbols index ce3836aacd4..3d6c4f2f960 100644 --- a/tests/baselines/reference/jqueryInference.symbols +++ b/tests/baselines/reference/jqueryInference.symbols @@ -48,7 +48,7 @@ var p2 = shouldBeIdentity(p1); >shouldBeIdentity : Symbol(shouldBeIdentity, Decl(jqueryInference.ts, 6, 58)) >p1 : Symbol(p1, Decl(jqueryInference.ts, 10, 13)) -var p2: MyPromise; +var p2: MyPromise; >p2 : Symbol(p2, Decl(jqueryInference.ts, 11, 3), Decl(jqueryInference.ts, 12, 3)) >MyPromise : Symbol(MyPromise, Decl(jqueryInference.ts, 0, 0)) diff --git a/tests/baselines/reference/jqueryInference.types b/tests/baselines/reference/jqueryInference.types index 5f055fe16b2..558b0f53df3 100644 --- a/tests/baselines/reference/jqueryInference.types +++ b/tests/baselines/reference/jqueryInference.types @@ -22,11 +22,11 @@ declare const p1: MyPromise; >p1 : MyPromise var p2 = shouldBeIdentity(p1); ->p2 : MyPromise ->shouldBeIdentity(p1) : MyPromise +>p2 : MyPromise +>shouldBeIdentity(p1) : MyPromise >shouldBeIdentity : (p: DoNothingAlias) => MyPromise >p1 : MyPromise -var p2: MyPromise; ->p2 : MyPromise +var p2: MyPromise; +>p2 : MyPromise From 35cf397ae3083536884304a27d9494be0a758b38 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sun, 10 Feb 2019 15:29:14 -0800 Subject: [PATCH 042/149] Add regression tests --- .../unionAndIntersectionInference1.ts | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/tests/cases/conformance/types/typeRelationships/typeInference/unionAndIntersectionInference1.ts b/tests/cases/conformance/types/typeRelationships/typeInference/unionAndIntersectionInference1.ts index 7066c3e6790..d4c7d25615e 100644 --- a/tests/cases/conformance/types/typeRelationships/typeInference/unionAndIntersectionInference1.ts +++ b/tests/cases/conformance/types/typeRelationships/typeInference/unionAndIntersectionInference1.ts @@ -1,3 +1,5 @@ +// @target: es2015 + // Repro from #2264 interface Y { 'i am a very certain type': Y } @@ -70,3 +72,21 @@ declare var mbp: Man & Bear; pigify(mbp).oinks; // OK, mbp is treated as Pig pigify(mbp).walks; // Ok, mbp is treated as Man + +// Repros from #29815 + +interface ITest { + name: 'test' +} + +const createTestAsync = (): Promise => Promise.resolve().then(() => ({ name: 'test' })) + +const createTest = (): ITest => { + return { name: 'test' } +} + +declare function f1(x: T | U): T | U; +declare function f2(x: T & U): T & U; + +let x1: string = f1('a'); +let x2: string = f2('a'); From 1c9fe44726535ad15ca742a6521eea8a0eec3475 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sun, 10 Feb 2019 15:29:22 -0800 Subject: [PATCH 043/149] Accept new baselines --- .../unionAndIntersectionInference1.js | 28 ++++++++- .../unionAndIntersectionInference1.symbols | 58 ++++++++++++++++++- .../unionAndIntersectionInference1.types | 53 +++++++++++++++++ 3 files changed, 136 insertions(+), 3 deletions(-) diff --git a/tests/baselines/reference/unionAndIntersectionInference1.js b/tests/baselines/reference/unionAndIntersectionInference1.js index 235eb23ebf8..ca9e527d99e 100644 --- a/tests/baselines/reference/unionAndIntersectionInference1.js +++ b/tests/baselines/reference/unionAndIntersectionInference1.js @@ -71,6 +71,24 @@ declare var mbp: Man & Bear; pigify(mbp).oinks; // OK, mbp is treated as Pig pigify(mbp).walks; // Ok, mbp is treated as Man + +// Repros from #29815 + +interface ITest { + name: 'test' +} + +const createTestAsync = (): Promise => Promise.resolve().then(() => ({ name: 'test' })) + +const createTest = (): ITest => { + return { name: 'test' } +} + +declare function f1(x: T | U): T | U; +declare function f2(x: T & U): T & U; + +let x1: string = f1('a'); +let x2: string = f2('a'); //// [unionAndIntersectionInference1.js] @@ -80,7 +98,7 @@ function destructure(something, haveValue, haveY) { return something === y ? haveY(y) : haveValue(something); } var value = Math.random() > 0.5 ? 'hey!' : undefined; -var result = destructure(value, function (text) { return 'string'; }, function (y) { return 'other one'; }); // text: string, y: Y +var result = destructure(value, text => 'string', y => 'other one'); // text: string, y: Y // Repro from #4212 function isVoid(value) { return undefined; @@ -107,7 +125,13 @@ function baz1(value) { function get(x) { return null; // just an example } -var foo; +let foo; get(foo).toUpperCase(); // Ok pigify(mbp).oinks; // OK, mbp is treated as Pig pigify(mbp).walks; // Ok, mbp is treated as Man +const createTestAsync = () => Promise.resolve().then(() => ({ name: 'test' })); +const createTest = () => { + return { name: 'test' }; +}; +let x1 = f1('a'); +let x2 = f2('a'); diff --git a/tests/baselines/reference/unionAndIntersectionInference1.symbols b/tests/baselines/reference/unionAndIntersectionInference1.symbols index 38bcd416dff..e866f19daa4 100644 --- a/tests/baselines/reference/unionAndIntersectionInference1.symbols +++ b/tests/baselines/reference/unionAndIntersectionInference1.symbols @@ -50,7 +50,7 @@ function destructure( var value = Math.random() > 0.5 ? 'hey!' : undefined; >value : Symbol(value, Decl(unionAndIntersectionInference1.ts, 12, 3)) >Math.random : Symbol(Math.random, Decl(lib.es5.d.ts, --, --)) ->Math : Symbol(Math, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>Math : Symbol(Math, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) >random : Symbol(Math.random, Decl(lib.es5.d.ts, --, --)) >Y : Symbol(Y, Decl(unionAndIntersectionInference1.ts, 0, 0)) >undefined : Symbol(undefined) @@ -201,3 +201,59 @@ pigify(mbp).walks; // Ok, mbp is treated as Man >mbp : Symbol(mbp, Decl(unionAndIntersectionInference1.ts, 68, 11)) >walks : Symbol(Man.walks, Decl(unionAndIntersectionInference1.ts, 55, 15)) +// Repros from #29815 + +interface ITest { +>ITest : Symbol(ITest, Decl(unionAndIntersectionInference1.ts, 71, 18)) + + name: 'test' +>name : Symbol(ITest.name, Decl(unionAndIntersectionInference1.ts, 75, 17)) +} + +const createTestAsync = (): Promise => Promise.resolve().then(() => ({ name: 'test' })) +>createTestAsync : Symbol(createTestAsync, Decl(unionAndIntersectionInference1.ts, 79, 5)) +>Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) +>ITest : Symbol(ITest, Decl(unionAndIntersectionInference1.ts, 71, 18)) +>Promise.resolve().then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) +>Promise.resolve : Symbol(PromiseConstructor.resolve, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --)) +>resolve : Symbol(PromiseConstructor.resolve, Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --)) +>then : Symbol(Promise.then, Decl(lib.es5.d.ts, --, --)) +>name : Symbol(name, Decl(unionAndIntersectionInference1.ts, 79, 77)) + +const createTest = (): ITest => { +>createTest : Symbol(createTest, Decl(unionAndIntersectionInference1.ts, 81, 5)) +>ITest : Symbol(ITest, Decl(unionAndIntersectionInference1.ts, 71, 18)) + + return { name: 'test' } +>name : Symbol(name, Decl(unionAndIntersectionInference1.ts, 82, 10)) +} + +declare function f1(x: T | U): T | U; +>f1 : Symbol(f1, Decl(unionAndIntersectionInference1.ts, 83, 1)) +>T : Symbol(T, Decl(unionAndIntersectionInference1.ts, 85, 20)) +>U : Symbol(U, Decl(unionAndIntersectionInference1.ts, 85, 22)) +>x : Symbol(x, Decl(unionAndIntersectionInference1.ts, 85, 26)) +>T : Symbol(T, Decl(unionAndIntersectionInference1.ts, 85, 20)) +>U : Symbol(U, Decl(unionAndIntersectionInference1.ts, 85, 22)) +>T : Symbol(T, Decl(unionAndIntersectionInference1.ts, 85, 20)) +>U : Symbol(U, Decl(unionAndIntersectionInference1.ts, 85, 22)) + +declare function f2(x: T & U): T & U; +>f2 : Symbol(f2, Decl(unionAndIntersectionInference1.ts, 85, 43)) +>T : Symbol(T, Decl(unionAndIntersectionInference1.ts, 86, 20)) +>U : Symbol(U, Decl(unionAndIntersectionInference1.ts, 86, 22)) +>x : Symbol(x, Decl(unionAndIntersectionInference1.ts, 86, 26)) +>T : Symbol(T, Decl(unionAndIntersectionInference1.ts, 86, 20)) +>U : Symbol(U, Decl(unionAndIntersectionInference1.ts, 86, 22)) +>T : Symbol(T, Decl(unionAndIntersectionInference1.ts, 86, 20)) +>U : Symbol(U, Decl(unionAndIntersectionInference1.ts, 86, 22)) + +let x1: string = f1('a'); +>x1 : Symbol(x1, Decl(unionAndIntersectionInference1.ts, 88, 3)) +>f1 : Symbol(f1, Decl(unionAndIntersectionInference1.ts, 83, 1)) + +let x2: string = f2('a'); +>x2 : Symbol(x2, Decl(unionAndIntersectionInference1.ts, 89, 3)) +>f2 : Symbol(f2, Decl(unionAndIntersectionInference1.ts, 85, 43)) + diff --git a/tests/baselines/reference/unionAndIntersectionInference1.types b/tests/baselines/reference/unionAndIntersectionInference1.types index 7b2515c6b58..4dddcb8bd0f 100644 --- a/tests/baselines/reference/unionAndIntersectionInference1.types +++ b/tests/baselines/reference/unionAndIntersectionInference1.types @@ -179,3 +179,56 @@ pigify(mbp).walks; // Ok, mbp is treated as Man >mbp : Man & Bear >walks : boolean +// Repros from #29815 + +interface ITest { + name: 'test' +>name : "test" +} + +const createTestAsync = (): Promise => Promise.resolve().then(() => ({ name: 'test' })) +>createTestAsync : () => Promise +>(): Promise => Promise.resolve().then(() => ({ name: 'test' })) : () => Promise +>Promise.resolve().then(() => ({ name: 'test' })) : Promise +>Promise.resolve().then : (onfulfilled?: (value: void) => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise +>Promise.resolve() : Promise +>Promise.resolve : { (value: T | PromiseLike): Promise; (): Promise; } +>Promise : PromiseConstructor +>resolve : { (value: T | PromiseLike): Promise; (): Promise; } +>then : (onfulfilled?: (value: void) => TResult1 | PromiseLike, onrejected?: (reason: any) => TResult2 | PromiseLike) => Promise +>() => ({ name: 'test' }) : () => { name: "test"; } +>({ name: 'test' }) : { name: "test"; } +>{ name: 'test' } : { name: "test"; } +>name : "test" +>'test' : "test" + +const createTest = (): ITest => { +>createTest : () => ITest +>(): ITest => { return { name: 'test' }} : () => ITest + + return { name: 'test' } +>{ name: 'test' } : { name: "test"; } +>name : "test" +>'test' : "test" +} + +declare function f1(x: T | U): T | U; +>f1 : (x: T | U) => T | U +>x : T | U + +declare function f2(x: T & U): T & U; +>f2 : (x: T & U) => T & U +>x : T & U + +let x1: string = f1('a'); +>x1 : string +>f1('a') : "a" +>f1 : (x: T | U) => T | U +>'a' : "a" + +let x2: string = f2('a'); +>x2 : string +>f2('a') : "a" +>f2 : (x: T & U) => T & U +>'a' : "a" + From 17d16d1bbb943e4c5ead1dfb50d0da53cc499693 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Mon, 11 Feb 2019 08:36:35 -0800 Subject: [PATCH 044/149] Disable checkJS survey (#29830) * Disable checkJS survey * Completely remove survey infrastructure * Re-instate the protocol part of SurveyReady --- src/server/editorServices.ts | 32 ----- src/server/project.ts | 2 - src/server/session.ts | 4 - src/testRunner/tsconfig.json | 1 - .../unittests/tsserver/events/surveyReady.ts | 111 ------------------ .../reference/api/tsserverlibrary.d.ts | 11 +- .../TypeScript-Node-Starter | 2 +- tests/cases/user/prettier/prettier | 2 +- tests/cases/user/webpack/webpack | 2 +- 9 files changed, 4 insertions(+), 163 deletions(-) delete mode 100644 src/testRunner/unittests/tsserver/events/surveyReady.ts diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index 6dccc08c4b5..e9d97f6e03c 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -7,7 +7,6 @@ namespace ts.server { export const ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground"; export const ProjectLoadingStartEvent = "projectLoadingStart"; export const ProjectLoadingFinishEvent = "projectLoadingFinish"; - export const SurveyReady = "surveyReady"; export const LargeFileReferencedEvent = "largeFileReferenced"; export const ConfigFileDiagEvent = "configFileDiag"; export const ProjectLanguageServiceStateEvent = "projectLanguageServiceState"; @@ -30,11 +29,6 @@ namespace ts.server { data: { project: Project; }; } - export interface SurveyReady { - eventName: typeof SurveyReady; - data: { surveyId: string; }; - } - export interface LargeFileReferencedEvent { eventName: typeof LargeFileReferencedEvent; data: { file: string; fileSize: number; maxFileSize: number; }; @@ -146,7 +140,6 @@ namespace ts.server { } export type ProjectServiceEvent = LargeFileReferencedEvent | - SurveyReady | ProjectsUpdatedInBackgroundEvent | ProjectLoadingStartEvent | ProjectLoadingFinishEvent | @@ -518,9 +511,6 @@ namespace ts.server { /** Tracks projects that we have already sent telemetry for. */ private readonly seenProjects = createMap(); - /** Tracks projects that we have already sent survey events for. */ - private readonly seenSurveyProjects = createMap(); - /*@internal*/ readonly watchFactory: WatchFactory; @@ -722,14 +712,6 @@ namespace ts.server { this.eventHandler(event); } - /* @internal */ - sendSurveyReadyEvent(surveyId: string) { - if (!this.eventHandler) { - return; - } - this.eventHandler({ eventName: SurveyReady, data: { surveyId } }); - } - /* @internal */ sendLargeFileReferencedEvent(file: string, fileSize: number) { if (!this.eventHandler) { @@ -1611,20 +1593,6 @@ namespace ts.server { return project; } - /*@internal*/ - sendSurveyReady(project: ExternalProject | ConfiguredProject): void { - if (this.seenSurveyProjects.has(project.projectName)) { - return; - } - - if (project.getCompilerOptions().checkJs !== undefined) { - const name = "checkJs"; - this.logger.info(`Survey ${name} is ready`); - this.sendSurveyReadyEvent(name); - this.seenSurveyProjects.set(project.projectName, true); - } - } - /*@internal*/ sendProjectTelemetry(project: ExternalProject | ConfiguredProject): void { if (this.seenProjects.has(project.projectName)) { diff --git a/src/server/project.ts b/src/server/project.ts index b296668e6ae..280cedb424d 100644 --- a/src/server/project.ts +++ b/src/server/project.ts @@ -1431,7 +1431,6 @@ namespace ts.server { } this.projectService.sendProjectLoadingFinishEvent(this); this.projectService.sendProjectTelemetry(this); - this.projectService.sendSurveyReady(this); return result; } @@ -1627,7 +1626,6 @@ namespace ts.server { updateGraph() { const result = super.updateGraph(); this.projectService.sendProjectTelemetry(this); - this.projectService.sendSurveyReady(this); return result; } diff --git a/src/server/session.ts b/src/server/session.ts index e5b128c984e..b47dfe6b716 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -610,10 +610,6 @@ namespace ts.server { diagnostics: bakedDiags }, ConfigFileDiagEvent); break; - case SurveyReady: - const { surveyId } = event.data; - this.event({ surveyId }, SurveyReady); - break; case ProjectLanguageServiceStateEvent: { const eventName: protocol.ProjectLanguageServiceStateEventName = ProjectLanguageServiceStateEvent; this.event({ diff --git a/src/testRunner/tsconfig.json b/src/testRunner/tsconfig.json index 7e75c0105a2..137e4d8af58 100644 --- a/src/testRunner/tsconfig.json +++ b/src/testRunner/tsconfig.json @@ -109,7 +109,6 @@ "unittests/tsserver/events/projectLanguageServiceState.ts", "unittests/tsserver/events/projectLoading.ts", "unittests/tsserver/events/projectUpdatedInBackground.ts", - "unittests/tsserver/events/surveyReady.ts", "unittests/tsserver/externalProjects.ts", "unittests/tsserver/forceConsistentCasingInFileNames.ts", "unittests/tsserver/formatSettings.ts", diff --git a/src/testRunner/unittests/tsserver/events/surveyReady.ts b/src/testRunner/unittests/tsserver/events/surveyReady.ts deleted file mode 100644 index b04746800d0..00000000000 --- a/src/testRunner/unittests/tsserver/events/surveyReady.ts +++ /dev/null @@ -1,111 +0,0 @@ -namespace ts.projectSystem { - describe("unittests:: tsserver:: events:: SurveyReady", () => { - function createSessionWithEventHandler(host: TestServerHost) { - const { session, events: surveyEvents } = createSessionWithEventTracking(host, server.SurveyReady); - - return { session, verifySurveyReadyEvent }; - - function verifySurveyReadyEvent(numberOfEvents: number) { - assert.equal(surveyEvents.length, numberOfEvents); - const expectedEvents = numberOfEvents === 0 ? [] : [{ - eventName: server.SurveyReady, - data: { surveyId: "checkJs" } - }]; - assert.deepEqual(surveyEvents, expectedEvents); - } - } - - it("doesn't log an event when checkJs isn't set", () => { - const projectRoot = "/user/username/projects/project"; - const file: File = { - path: `${projectRoot}/src/file.ts`, - content: "export var y = 10;" - }; - const tsconfig: File = { - path: `${projectRoot}/tsconfig.json`, - content: JSON.stringify({ compilerOptions: {} }), - }; - const host = createServerHost([file, tsconfig]); - const { session, verifySurveyReadyEvent } = createSessionWithEventHandler(host); - const service = session.getProjectService(); - openFilesForSession([file], session); - checkNumberOfProjects(service, { configuredProjects: 1 }); - const project = service.configuredProjects.get(tsconfig.path)!; - checkProjectActualFiles(project, [file.path, tsconfig.path]); - - verifySurveyReadyEvent(0); - }); - - it("logs an event when checkJs is set", () => { - const projectRoot = "/user/username/projects/project"; - const file: File = { - path: `${projectRoot}/src/file.ts`, - content: "export var y = 10;" - }; - const tsconfig: File = { - path: `${projectRoot}/tsconfig.json`, - content: JSON.stringify({ compilerOptions: { checkJs: true } }), - }; - const host = createServerHost([file, tsconfig]); - const { session, verifySurveyReadyEvent } = createSessionWithEventHandler(host); - openFilesForSession([file], session); - - verifySurveyReadyEvent(1); - }); - - it("logs an event when checkJs is set, only the first time", () => { - const projectRoot = "/user/username/projects/project"; - const file: File = { - path: `${projectRoot}/src/file.ts`, - content: "export var y = 10;" - }; - const rando: File = { - path: `/rando/calrissian.ts`, - content: "export function f() { }" - }; - const tsconfig: File = { - path: `${projectRoot}/tsconfig.json`, - content: JSON.stringify({ compilerOptions: { checkJs: true } }), - }; - const host = createServerHost([file, tsconfig]); - const { session, verifySurveyReadyEvent } = createSessionWithEventHandler(host); - openFilesForSession([file], session); - - verifySurveyReadyEvent(1); - - closeFilesForSession([file], session); - openFilesForSession([rando], session); - openFilesForSession([file], session); - - verifySurveyReadyEvent(1); - }); - - it("logs an event when checkJs is set after closing and reopening", () => { - const projectRoot = "/user/username/projects/project"; - const file: File = { - path: `${projectRoot}/src/file.ts`, - content: "export var y = 10;" - }; - const rando: File = { - path: `/rando/calrissian.ts`, - content: "export function f() { }" - }; - const tsconfig: File = { - path: `${projectRoot}/tsconfig.json`, - content: JSON.stringify({}), - }; - const host = createServerHost([file, tsconfig]); - const { session, verifySurveyReadyEvent } = createSessionWithEventHandler(host); - openFilesForSession([file], session); - - verifySurveyReadyEvent(0); - - closeFilesForSession([file], session); - openFilesForSession([rando], session); - host.writeFile(tsconfig.path, JSON.stringify({ compilerOptions: { checkJs: true } })); - openFilesForSession([file], session); - - verifySurveyReadyEvent(1); - }); - }); -} diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 025880dc09e..36c246c999f 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -8357,7 +8357,6 @@ declare namespace ts.server { const ProjectsUpdatedInBackgroundEvent = "projectsUpdatedInBackground"; const ProjectLoadingStartEvent = "projectLoadingStart"; const ProjectLoadingFinishEvent = "projectLoadingFinish"; - const SurveyReady = "surveyReady"; const LargeFileReferencedEvent = "largeFileReferenced"; const ConfigFileDiagEvent = "configFileDiag"; const ProjectLanguageServiceStateEvent = "projectLanguageServiceState"; @@ -8382,12 +8381,6 @@ declare namespace ts.server { project: Project; }; } - interface SurveyReady { - eventName: typeof SurveyReady; - data: { - surveyId: string; - }; - } interface LargeFileReferencedEvent { eventName: typeof LargeFileReferencedEvent; data: { @@ -8472,7 +8465,7 @@ declare namespace ts.server { interface OpenFileInfo { readonly checkJs: boolean; } - type ProjectServiceEvent = LargeFileReferencedEvent | SurveyReady | ProjectsUpdatedInBackgroundEvent | ProjectLoadingStartEvent | ProjectLoadingFinishEvent | ConfigFileDiagEvent | ProjectLanguageServiceStateEvent | ProjectInfoTelemetryEvent | OpenFileInfoTelemetryEvent; + type ProjectServiceEvent = LargeFileReferencedEvent | ProjectsUpdatedInBackgroundEvent | ProjectLoadingStartEvent | ProjectLoadingFinishEvent | ConfigFileDiagEvent | ProjectLanguageServiceStateEvent | ProjectInfoTelemetryEvent | OpenFileInfoTelemetryEvent; type ProjectServiceEventHandler = (event: ProjectServiceEvent) => void; interface SafeList { [name: string]: { @@ -8589,8 +8582,6 @@ declare namespace ts.server { readonly syntaxOnly?: boolean; /** Tracks projects that we have already sent telemetry for. */ private readonly seenProjects; - /** Tracks projects that we have already sent survey events for. */ - private readonly seenSurveyProjects; constructor(opts: ProjectServiceOptions); toPath(fileName: string): Path; private loadTypesMap; diff --git a/tests/cases/user/TypeScript-Node-Starter/TypeScript-Node-Starter b/tests/cases/user/TypeScript-Node-Starter/TypeScript-Node-Starter index 40bdb4eadab..6b9706810b5 160000 --- a/tests/cases/user/TypeScript-Node-Starter/TypeScript-Node-Starter +++ b/tests/cases/user/TypeScript-Node-Starter/TypeScript-Node-Starter @@ -1 +1 @@ -Subproject commit 40bdb4eadabc9fbed7d83e3f26817a931c0763b6 +Subproject commit 6b9706810b55af326a93b9aa59cb17815a30bb32 diff --git a/tests/cases/user/prettier/prettier b/tests/cases/user/prettier/prettier index 67f1c4877ee..6e0de081223 160000 --- a/tests/cases/user/prettier/prettier +++ b/tests/cases/user/prettier/prettier @@ -1 +1 @@ -Subproject commit 67f1c4877ee1090b66d468a847caccca411a6f82 +Subproject commit 6e0de0812231c3a48387d398d092418749aa39f1 diff --git a/tests/cases/user/webpack/webpack b/tests/cases/user/webpack/webpack index 10282ea2064..a28f44f6132 160000 --- a/tests/cases/user/webpack/webpack +++ b/tests/cases/user/webpack/webpack @@ -1 +1 @@ -Subproject commit 10282ea20648b465caec6448849f24fc34e1ba3e +Subproject commit a28f44f613276446fb764dec7fab38b7cff8a07c From 36be6c8b6859ea5b8a18e375609133311fd0cce3 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Mon, 11 Feb 2019 09:41:38 -0800 Subject: [PATCH 045/149] Accept new baselines --- .../restTuplesFromContextualTypes.errors.txt | 12 ++++++------ .../reference/restTuplesFromContextualTypes.types | 10 +++++----- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/tests/baselines/reference/restTuplesFromContextualTypes.errors.txt b/tests/baselines/reference/restTuplesFromContextualTypes.errors.txt index d2246fbfd84..7af71017a71 100644 --- a/tests/baselines/reference/restTuplesFromContextualTypes.errors.txt +++ b/tests/baselines/reference/restTuplesFromContextualTypes.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/types/rest/restTuplesFromContextualTypes.ts(56,7): error TS2345: Argument of type '(a: number, b: any, ...x: any[]) => void' is not assignable to parameter of type '(x: number, ...args: T) => void'. +tests/cases/conformance/types/rest/restTuplesFromContextualTypes.ts(56,7): error TS2345: Argument of type '(a: number, b: T[0], ...x: T[number][]) => void' is not assignable to parameter of type '(x: number, ...args: T) => void'. Types of parameters 'b' and 'args' are incompatible. - Type 'T' is not assignable to type '[any, ...any[]]'. - Property '0' is missing in type 'any[]' but required in type '[any, ...any[]]'. + Type 'T' is not assignable to type '[T[0], ...T[number][]]'. + Property '0' is missing in type 'any[]' but required in type '[T[0], ...T[number][]]'. ==== tests/cases/conformance/types/rest/restTuplesFromContextualTypes.ts (1 errors) ==== @@ -62,10 +62,10 @@ tests/cases/conformance/types/rest/restTuplesFromContextualTypes.ts(56,7): error f((a, ...x) => {}); f((a, b, ...x) => {}); ~~~~~~~~~~~~~~~~~~ -!!! error TS2345: Argument of type '(a: number, b: any, ...x: any[]) => void' is not assignable to parameter of type '(x: number, ...args: T) => void'. +!!! error TS2345: Argument of type '(a: number, b: T[0], ...x: T[number][]) => void' is not assignable to parameter of type '(x: number, ...args: T) => void'. !!! error TS2345: Types of parameters 'b' and 'args' are incompatible. -!!! error TS2345: Type 'T' is not assignable to type '[any, ...any[]]'. -!!! error TS2345: Property '0' is missing in type 'any[]' but required in type '[any, ...any[]]'. +!!! error TS2345: Type 'T' is not assignable to type '[T[0], ...T[number][]]'. +!!! error TS2345: Property '0' is missing in type 'any[]' but required in type '[T[0], ...T[number][]]'. } // Repro from #25288 diff --git a/tests/baselines/reference/restTuplesFromContextualTypes.types b/tests/baselines/reference/restTuplesFromContextualTypes.types index ee63057b9eb..ad5a4788426 100644 --- a/tests/baselines/reference/restTuplesFromContextualTypes.types +++ b/tests/baselines/reference/restTuplesFromContextualTypes.types @@ -332,8 +332,8 @@ function f4(t: T) { f((...x) => {}); >f((...x) => {}) : void >f : (cb: (x: number, ...args: T) => void) => void ->(...x) => {} : (x: number, ...args: any[]) => void ->x : [number, ...any[]] +>(...x) => {} : (x: number, ...args: T[number][]) => void +>x : [number, ...T[number][]] f((a, ...x) => {}); >f((a, ...x) => {}) : void @@ -345,10 +345,10 @@ function f4(t: T) { f((a, b, ...x) => {}); >f((a, b, ...x) => {}) : void >f : (cb: (x: number, ...args: T) => void) => void ->(a, b, ...x) => {} : (a: number, b: any, ...x: any[]) => void +>(a, b, ...x) => {} : (a: number, b: T[0], ...x: T[number][]) => void >a : number ->b : any ->x : any[] +>b : T[0] +>x : T[number][] } // Repro from #25288 From 710826e37e9fc2627e1c4ea2746645d1befb7b89 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Mon, 11 Feb 2019 09:46:02 -0800 Subject: [PATCH 046/149] Add regression test --- .../types/rest/restTuplesFromContextualTypes.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/tests/cases/conformance/types/rest/restTuplesFromContextualTypes.ts b/tests/cases/conformance/types/rest/restTuplesFromContextualTypes.ts index 84bf81195b0..d5623a000a2 100644 --- a/tests/cases/conformance/types/rest/restTuplesFromContextualTypes.ts +++ b/tests/cases/conformance/types/rest/restTuplesFromContextualTypes.ts @@ -70,3 +70,17 @@ declare function take(cb: (a: number, b: string) => void): void; (function foo(...rest){}(1, '')); take(function(...rest){}); + +// Repro from #29833 + +type ArgsUnion = [number, string] | [number, Error]; +type TupleUnionFunc = (...params: ArgsUnion) => number; + +const funcUnionTupleNoRest: TupleUnionFunc = (num, strOrErr) => { + return num; +}; + +const funcUnionTupleRest: TupleUnionFunc = (...params) => { + const [num, strOrErr] = params; + return num; +}; From f33c740b8c29d5b2b07ec6d01422ccd16e7a0d63 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Mon, 11 Feb 2019 09:46:10 -0800 Subject: [PATCH 047/149] Accept new baselines --- .../restTuplesFromContextualTypes.errors.txt | 14 +++++++ .../restTuplesFromContextualTypes.js | 29 +++++++++++++++ .../restTuplesFromContextualTypes.symbols | 37 +++++++++++++++++++ .../restTuplesFromContextualTypes.types | 35 ++++++++++++++++++ 4 files changed, 115 insertions(+) diff --git a/tests/baselines/reference/restTuplesFromContextualTypes.errors.txt b/tests/baselines/reference/restTuplesFromContextualTypes.errors.txt index 7af71017a71..2b94b57f462 100644 --- a/tests/baselines/reference/restTuplesFromContextualTypes.errors.txt +++ b/tests/baselines/reference/restTuplesFromContextualTypes.errors.txt @@ -79,4 +79,18 @@ tests/cases/conformance/types/rest/restTuplesFromContextualTypes.ts(56,7): error (function foo(...rest){}(1, '')); take(function(...rest){}); + + // Repro from #29833 + + type ArgsUnion = [number, string] | [number, Error]; + type TupleUnionFunc = (...params: ArgsUnion) => number; + + const funcUnionTupleNoRest: TupleUnionFunc = (num, strOrErr) => { + return num; + }; + + const funcUnionTupleRest: TupleUnionFunc = (...params) => { + const [num, strOrErr] = params; + return num; + }; \ No newline at end of file diff --git a/tests/baselines/reference/restTuplesFromContextualTypes.js b/tests/baselines/reference/restTuplesFromContextualTypes.js index 3db6c53f384..34e75fcea6e 100644 --- a/tests/baselines/reference/restTuplesFromContextualTypes.js +++ b/tests/baselines/reference/restTuplesFromContextualTypes.js @@ -68,6 +68,20 @@ declare function take(cb: (a: number, b: string) => void): void; (function foo(...rest){}(1, '')); take(function(...rest){}); + +// Repro from #29833 + +type ArgsUnion = [number, string] | [number, Error]; +type TupleUnionFunc = (...params: ArgsUnion) => number; + +const funcUnionTupleNoRest: TupleUnionFunc = (num, strOrErr) => { + return num; +}; + +const funcUnionTupleRest: TupleUnionFunc = (...params) => { + const [num, strOrErr] = params; + return num; +}; //// [restTuplesFromContextualTypes.js] @@ -274,6 +288,17 @@ take(function () { rest[_i] = arguments[_i]; } }); +var funcUnionTupleNoRest = function (num, strOrErr) { + return num; +}; +var funcUnionTupleRest = function () { + var params = []; + for (var _i = 0; _i < arguments.length; _i++) { + params[_i] = arguments[_i]; + } + var num = params[0], strOrErr = params[1]; + return num; +}; //// [restTuplesFromContextualTypes.d.ts] @@ -286,3 +311,7 @@ declare function f3(cb: (x: number, ...args: typeof t3) => void): void; declare function f4(t: T): void; declare var tuple: [number, string]; declare function take(cb: (a: number, b: string) => void): void; +declare type ArgsUnion = [number, string] | [number, Error]; +declare type TupleUnionFunc = (...params: ArgsUnion) => number; +declare const funcUnionTupleNoRest: TupleUnionFunc; +declare const funcUnionTupleRest: TupleUnionFunc; diff --git a/tests/baselines/reference/restTuplesFromContextualTypes.symbols b/tests/baselines/reference/restTuplesFromContextualTypes.symbols index d9b2310b5e2..c58e8cabcae 100644 --- a/tests/baselines/reference/restTuplesFromContextualTypes.symbols +++ b/tests/baselines/reference/restTuplesFromContextualTypes.symbols @@ -265,3 +265,40 @@ take(function(...rest){}); >take : Symbol(take, Decl(restTuplesFromContextualTypes.ts, 61, 33)) >rest : Symbol(rest, Decl(restTuplesFromContextualTypes.ts, 68, 14)) +// Repro from #29833 + +type ArgsUnion = [number, string] | [number, Error]; +>ArgsUnion : Symbol(ArgsUnion, Decl(restTuplesFromContextualTypes.ts, 68, 26)) +>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) + +type TupleUnionFunc = (...params: ArgsUnion) => number; +>TupleUnionFunc : Symbol(TupleUnionFunc, Decl(restTuplesFromContextualTypes.ts, 72, 52)) +>params : Symbol(params, Decl(restTuplesFromContextualTypes.ts, 73, 23)) +>ArgsUnion : Symbol(ArgsUnion, Decl(restTuplesFromContextualTypes.ts, 68, 26)) + +const funcUnionTupleNoRest: TupleUnionFunc = (num, strOrErr) => { +>funcUnionTupleNoRest : Symbol(funcUnionTupleNoRest, Decl(restTuplesFromContextualTypes.ts, 75, 5)) +>TupleUnionFunc : Symbol(TupleUnionFunc, Decl(restTuplesFromContextualTypes.ts, 72, 52)) +>num : Symbol(num, Decl(restTuplesFromContextualTypes.ts, 75, 46)) +>strOrErr : Symbol(strOrErr, Decl(restTuplesFromContextualTypes.ts, 75, 50)) + + return num; +>num : Symbol(num, Decl(restTuplesFromContextualTypes.ts, 75, 46)) + +}; + +const funcUnionTupleRest: TupleUnionFunc = (...params) => { +>funcUnionTupleRest : Symbol(funcUnionTupleRest, Decl(restTuplesFromContextualTypes.ts, 79, 5)) +>TupleUnionFunc : Symbol(TupleUnionFunc, Decl(restTuplesFromContextualTypes.ts, 72, 52)) +>params : Symbol(params, Decl(restTuplesFromContextualTypes.ts, 79, 44)) + + const [num, strOrErr] = params; +>num : Symbol(num, Decl(restTuplesFromContextualTypes.ts, 80, 9)) +>strOrErr : Symbol(strOrErr, Decl(restTuplesFromContextualTypes.ts, 80, 13)) +>params : Symbol(params, Decl(restTuplesFromContextualTypes.ts, 79, 44)) + + return num; +>num : Symbol(num, Decl(restTuplesFromContextualTypes.ts, 80, 9)) + +}; + diff --git a/tests/baselines/reference/restTuplesFromContextualTypes.types b/tests/baselines/reference/restTuplesFromContextualTypes.types index ad5a4788426..c282dbbae31 100644 --- a/tests/baselines/reference/restTuplesFromContextualTypes.types +++ b/tests/baselines/reference/restTuplesFromContextualTypes.types @@ -389,3 +389,38 @@ take(function(...rest){}); >function(...rest){} : (a: number, b: string) => void >rest : [number, string] +// Repro from #29833 + +type ArgsUnion = [number, string] | [number, Error]; +>ArgsUnion : ArgsUnion + +type TupleUnionFunc = (...params: ArgsUnion) => number; +>TupleUnionFunc : TupleUnionFunc +>params : ArgsUnion + +const funcUnionTupleNoRest: TupleUnionFunc = (num, strOrErr) => { +>funcUnionTupleNoRest : TupleUnionFunc +>(num, strOrErr) => { return num;} : (num: number, strOrErr: string | Error) => number +>num : number +>strOrErr : string | Error + + return num; +>num : number + +}; + +const funcUnionTupleRest: TupleUnionFunc = (...params) => { +>funcUnionTupleRest : TupleUnionFunc +>(...params) => { const [num, strOrErr] = params; return num;} : (...params: ArgsUnion) => number +>params : ArgsUnion + + const [num, strOrErr] = params; +>num : number +>strOrErr : string | Error +>params : ArgsUnion + + return num; +>num : number + +}; + From 1f10e74abc0aad67c1064abd51a77bcc2808e8e6 Mon Sep 17 00:00:00 2001 From: Ryan Cavanaugh Date: Mon, 11 Feb 2019 11:18:29 -0800 Subject: [PATCH 048/149] Enable no-eval rule --- src/harness/evaluator.ts | 1 + src/harness/fourslash.ts | 1 + src/harness/harness.ts | 1 + tslint.json | 2 +- 4 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/harness/evaluator.ts b/src/harness/evaluator.ts index 168fda1d767..a22bdb958bc 100644 --- a/src/harness/evaluator.ts +++ b/src/harness/evaluator.ts @@ -56,6 +56,7 @@ namespace evaluator { } const evaluateText = `(function (module, exports, require, __dirname, __filename, ${globalNames.join(", ")}) { ${output.text} })`; + // tslint:disable-next-line:no-eval const evaluateThunk = eval(evaluateText) as (module: any, exports: any, require: (id: string) => any, dirname: string, filename: string, ...globalArgs: any[]) => void; const module: { exports: any; } = { exports: {} }; evaluateThunk.call(globals, module, module.exports, noRequire, vpath.dirname(output.file), output.file, FakeSymbol, ...globalArgs); diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index b0bb35d5db3..f3a7197e777 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -3159,6 +3159,7 @@ ${code} const debug = new FourSlashInterface.Debug(state); const format = new FourSlashInterface.Format(state); const cancellation = new FourSlashInterface.Cancellation(state); + // tslint:disable-next-line:no-eval const f = eval(wrappedCode); f(test, goTo, plugins, verify, edit, debug, format, cancellation, FourSlashInterface.Classification, FourSlashInterface.Completion, verifyOperationIsCancelled); } diff --git a/src/harness/harness.ts b/src/harness/harness.ts index 13ef2adbf90..a78a04c3ecb 100644 --- a/src/harness/harness.ts +++ b/src/harness/harness.ts @@ -77,6 +77,7 @@ namespace Utils { const environment = getExecutionEnvironment(); switch (environment) { case ExecutionEnvironment.Browser: + // tslint:disable-next-line:no-eval eval(fileContents); break; case ExecutionEnvironment.Node: diff --git a/tslint.json b/tslint.json index a3ca10e75ed..488c6a8d003 100644 --- a/tslint.json +++ b/tslint.json @@ -34,6 +34,7 @@ ], "no-bom": true, "no-double-space": true, + "no-eval": true, "no-in-operator": true, "no-increment-decrement": true, "no-inferrable-types": true, @@ -100,7 +101,6 @@ "no-console": false, "no-debugger": false, "no-empty-interface": false, - "no-eval": false, "no-object-literal-type-assertion": false, "no-shadowed-variable": false, "no-submodule-imports": false, From 02a5ef6a179c9a08a410b6d042c45a47ec13cb42 Mon Sep 17 00:00:00 2001 From: Ryan Cavanaugh Date: Mon, 11 Feb 2019 11:26:19 -0800 Subject: [PATCH 049/149] Add setInterval/setTimeout --- src/harness/harnessLanguageService.ts | 1 + src/testRunner/parallel/host.ts | 2 ++ src/tsserver/server.ts | 1 + tslint.json | 5 +++++ 4 files changed, 9 insertions(+) diff --git a/src/harness/harnessLanguageService.ts b/src/harness/harnessLanguageService.ts index a78ef88e5b7..b70afecb791 100644 --- a/src/harness/harnessLanguageService.ts +++ b/src/harness/harnessLanguageService.ts @@ -766,6 +766,7 @@ namespace Harness.LanguageService { } setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): any { + // tslint:disable-next-line:ban return setTimeout(callback, ms, args); } diff --git a/src/testRunner/parallel/host.ts b/src/testRunner/parallel/host.ts index 376896a4697..9adf9e7e850 100644 --- a/src/testRunner/parallel/host.ts +++ b/src/testRunner/parallel/host.ts @@ -302,6 +302,7 @@ namespace Harness.Parallel.Host { worker.timer = undefined; } else { + // tslint:disable-next-line:ban worker.timer = setTimeout(killChild, data.payload.duration, data.payload); } break; @@ -623,6 +624,7 @@ namespace Harness.Parallel.Host { shimNoopTestInterface(global); } + // tslint:disable-next-line:ban setTimeout(() => startDelayed(perfData, totalCost), 0); // Do real startup on next tick, so all unit tests have been collected } } diff --git a/src/tsserver/server.ts b/src/tsserver/server.ts index 21146958748..0dc57ca520a 100644 --- a/src/tsserver/server.ts +++ b/src/tsserver/server.ts @@ -705,6 +705,7 @@ namespace ts.server { // stat due to inconsistencies of fs.watch // and efficiency of stat on modern filesystems function startWatchTimer() { + // tslint:disable-next-line:ban setInterval(() => { let count = 0; let nextToCheck = nextFileToCheck; diff --git a/tslint.json b/tslint.json index 488c6a8d003..5952c770c5e 100644 --- a/tslint.json +++ b/tslint.json @@ -5,6 +5,11 @@ "no-unnecessary-type-assertion": true, "array-type": [true, "array"], + "ban": [ + true, + "setInterval", + "setTimeout" + ], "ban-types": { "options": [ ["Object", "Avoid using the `Object` type. Did you mean `object`?"], From 26f8ddd46a7c1dd528f1812bd647b5135118be53 Mon Sep 17 00:00:00 2001 From: Gabriela Araujo Britto Date: Mon, 11 Feb 2019 12:01:02 -0800 Subject: [PATCH 050/149] create functions for copying trailing comments and rename previous copyComment function --- .../codefixes/convertFunctionToEs6Class.ts | 10 ++--- .../addOrRemoveBracesToArrowFunction.ts | 4 +- src/services/utilities.ts | 43 ++++++++++++++++++- 3 files changed, 49 insertions(+), 8 deletions(-) diff --git a/src/services/codefixes/convertFunctionToEs6Class.ts b/src/services/codefixes/convertFunctionToEs6Class.ts index 78e10ce2044..b87a78106ad 100644 --- a/src/services/codefixes/convertFunctionToEs6Class.ts +++ b/src/services/codefixes/convertFunctionToEs6Class.ts @@ -35,7 +35,7 @@ namespace ts.codefix { precedingNode = ctorDeclaration.parent.parent; newClassDeclaration = createClassFromVariableDeclaration(ctorDeclaration as VariableDeclaration); if ((ctorDeclaration.parent).declarations.length === 1) { - copyComments(precedingNode, newClassDeclaration!, sourceFile); // TODO: GH#18217 + copyLeadingComments(precedingNode, newClassDeclaration!, sourceFile); // TODO: GH#18217 changes.delete(sourceFile, precedingNode); } else { @@ -48,7 +48,7 @@ namespace ts.codefix { return undefined; } - copyComments(ctorDeclaration, newClassDeclaration, sourceFile); + copyLeadingComments(ctorDeclaration, newClassDeclaration, sourceFile); // Because the preceding node could be touched, we need to insert nodes before delete nodes. changes.insertNodeAfter(sourceFile, precedingNode!, newClassDeclaration); @@ -112,7 +112,7 @@ namespace ts.codefix { const fullModifiers = concatenate(modifiers, getModifierKindFromSource(functionExpression, SyntaxKind.AsyncKeyword)); const method = createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, /*typeParameters*/ undefined, functionExpression.parameters, /*type*/ undefined, functionExpression.body); - copyComments(assignmentBinaryExpression, method, sourceFile); + copyLeadingComments(assignmentBinaryExpression, method, sourceFile); return method; } @@ -132,7 +132,7 @@ namespace ts.codefix { const fullModifiers = concatenate(modifiers, getModifierKindFromSource(arrowFunction, SyntaxKind.AsyncKeyword)); const method = createMethod(/*decorators*/ undefined, fullModifiers, /*asteriskToken*/ undefined, memberDeclaration.name, /*questionToken*/ undefined, /*typeParameters*/ undefined, arrowFunction.parameters, /*type*/ undefined, bodyBlock); - copyComments(assignmentBinaryExpression, method, sourceFile); + copyLeadingComments(assignmentBinaryExpression, method, sourceFile); return method; } @@ -143,7 +143,7 @@ namespace ts.codefix { } const prop = createProperty(/*decorators*/ undefined, modifiers, memberDeclaration.name, /*questionToken*/ undefined, /*type*/ undefined, assignmentBinaryExpression.right); - copyComments(assignmentBinaryExpression.parent, prop, sourceFile); + copyLeadingComments(assignmentBinaryExpression.parent, prop, sourceFile); return prop; } } diff --git a/src/services/refactors/addOrRemoveBracesToArrowFunction.ts b/src/services/refactors/addOrRemoveBracesToArrowFunction.ts index c5fccde13db..97d6f4d6667 100644 --- a/src/services/refactors/addOrRemoveBracesToArrowFunction.ts +++ b/src/services/refactors/addOrRemoveBracesToArrowFunction.ts @@ -48,13 +48,13 @@ namespace ts.refactor.addOrRemoveBracesToArrowFunction { const returnStatement = createReturn(expression); body = createBlock([returnStatement], /* multiLine */ true); suppressLeadingAndTrailingTrivia(body); - copyComments(expression!, returnStatement, file, SyntaxKind.MultiLineCommentTrivia, /* hasTrailingNewLine */ true); + copyLeadingComments(expression!, returnStatement, file, SyntaxKind.MultiLineCommentTrivia, /* hasTrailingNewLine */ true); } else if (actionName === removeBracesActionName && returnStatement) { const actualExpression = expression || createVoidZero(); body = needsParentheses(actualExpression) ? createParen(actualExpression) : actualExpression; suppressLeadingAndTrailingTrivia(body); - copyComments(returnStatement, body, file, SyntaxKind.MultiLineCommentTrivia, /* hasTrailingNewLine */ false); + copyLeadingComments(returnStatement, body, file, SyntaxKind.MultiLineCommentTrivia, /* hasTrailingNewLine */ false); } else { Debug.fail("invalid action"); diff --git a/src/services/utilities.ts b/src/services/utilities.ts index 2b6d0acde88..46ec160c022 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -1831,7 +1831,7 @@ namespace ts { return lastPos; } - export function copyComments(sourceNode: Node, targetNode: Node, sourceFile: SourceFile, commentKind?: CommentKind, hasTrailingNewLine?: boolean) { + export function copyLeadingComments(sourceNode: Node, targetNode: Node, sourceFile: SourceFile, commentKind?: CommentKind, hasTrailingNewLine?: boolean) { forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, (pos, end, kind, htnl) => { if (kind === SyntaxKind.MultiLineCommentTrivia) { // Remove leading /* @@ -1847,6 +1847,47 @@ namespace ts { }); } + export function copyTrailingComments(sourceNode: Node, targetNode: Node, sourceFile: SourceFile, commentKind?: CommentKind, hasTrailingNewLine?: boolean) { + forEachTrailingCommentRange(sourceFile.text, sourceNode.end, (pos, end, kind, htnl) => { + if (kind === SyntaxKind.MultiLineCommentTrivia) { + // Remove leading /* + pos += 2; + // Remove trailing */ + end -= 2; + } + else { + // Remove leading // + pos += 2; + } + addSyntheticTrailingComment(targetNode, commentKind || kind, sourceFile.text.slice(pos, end), hasTrailingNewLine !== undefined ? hasTrailingNewLine : htnl); + }); + } + + /** + * This function copies the trailing comments for the token that comes before `sourceNode`, as leading comments of `targetNode`. + * This is useful because sometimes a comment that refers to `sourceNode` will be a leading comment for `sourceNode`, according to the + * notion of trivia ownership, and instead will be a trailing comment for the token before `sourceNode`, e.g.: + * `function foo(\* not leading comment for a *\ a: string) {}` + * The comment refers to `a` but belongs to the `(` token, but we might want to copy it. + */ + export function copyTrailingAsLeadingComments(sourceNode: Node, targetNode: Node, sourceFile: SourceFile, commentKind?: CommentKind, hasTrailingNewLine?: boolean) { + forEachTrailingCommentRange(sourceFile.text, sourceNode.pos, (pos, end, kind, htnl) => { + if (kind === SyntaxKind.MultiLineCommentTrivia) { + // Remove leading /* + pos += 2; + // Remove trailing */ + end -= 2; + } + else { + // Remove leading // + pos += 2; + } + addSyntheticLeadingComment(targetNode, commentKind || kind, sourceFile.text.slice(pos, end), hasTrailingNewLine !== undefined ? hasTrailingNewLine : htnl); + }); + } + + + function indexInTextChange(change: string, name: string): number { if (startsWith(change, name)) return 0; // Add a " " to avoid references inside words From dba631de80784f99a5fd946460ca27a54ad18a01 Mon Sep 17 00:00:00 2001 From: Gabriela Araujo Britto Date: Mon, 11 Feb 2019 12:02:51 -0800 Subject: [PATCH 051/149] copy comments when refactoring --- .../refactors/convertToNamedParameters.ts | 83 +++++++++++++++++-- 1 file changed, 74 insertions(+), 9 deletions(-) diff --git a/src/services/refactors/convertToNamedParameters.ts b/src/services/refactors/convertToNamedParameters.ts index 16716bed106..41c9935deb6 100644 --- a/src/services/refactors/convertToNamedParameters.ts +++ b/src/services/refactors/convertToNamedParameters.ts @@ -40,18 +40,26 @@ namespace ts.refactor.convertToNamedParameters { suppressLeadingAndTrailingTrivia(newFunctionDeclaration, /*recursive*/ false); changes.replaceNode(sourceFile, functionDeclaration, newFunctionDeclaration); - const nameNodes = getFunctionDeclarationNames(functionDeclaration); - const functionRefs = flatMap(nameNodes, name => FindAllReferences.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken)); + const functionNames = getFunctionDeclarationNames(functionDeclaration); + const functionRefs = flatMap(functionNames, name => FindAllReferences.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken)); const functionCalls = deduplicate(getDirectFunctionCalls(functionRefs), (a, b) => a === b); refactorSucceeded = true; // TODO: check if a bad reference was found forEach(functionCalls, call => { if (call.arguments && call.arguments.length) { - const newArguments = getSynthesizedDeepClone(createNewArguments(functionDeclaration, call.arguments), /*includeTrivia*/ true); - changes.replaceNodeRange(getSourceFileOfNode(call), first(call.arguments), last(call.arguments), newArguments); + const newArgument = getSynthesizedDeepClone(createNewArguments(functionDeclaration, call.arguments), /*includeTrivia*/ true); + const newCall = updateCallArguments(call, createNodeArray([newArgument])); + suppressLeadingAndTrailingTrivia(newCall, /*recursive*/ false); + changes.replaceNode(getSourceFileOfNode(call), call, newCall); }}); } + function updateCallArguments(call: CallExpression | NewExpression, args: NodeArray) { + const newCall = getSynthesizedClone(call); + newCall.arguments = args; + return updateNode(newCall, call); + } + function updateDeclarationParameters(declaration: SignatureDeclaration, parameters: NodeArray): SignatureDeclaration { const newDeclaration = getSynthesizedClone(declaration); newDeclaration.parameters = parameters; @@ -160,7 +168,12 @@ namespace ts.refactor.convertToNamedParameters { const parameters = getRefactorableParameters(functionDeclaration.parameters); const hasRestParameter = isRestParameter(last(parameters)); const nonRestArguments = hasRestParameter ? args.slice(0, parameters.length - 1) : args; - const properties = map(nonRestArguments, (arg, i) => createPropertyAssignment(getParameterName(parameters[i]), arg)); + const properties = map(nonRestArguments, (arg, i) => { + const property = createPropertyAssignment(getParameterName(parameters[i]), arg); + suppressLeadingAndTrailingTrivia(property.initializer); + copyComments(arg, property.initializer); + return property; + }); if (hasRestParameter && args.length >= parameters.length) { const restArguments = args.slice(parameters.length - 1); @@ -168,7 +181,8 @@ namespace ts.refactor.convertToNamedParameters { properties.push(restProperty); } - return createObjectLiteral(properties, /*multiLine*/ false); + const objectLiteral = createObjectLiteral(properties, /*multiLine*/ false); + return objectLiteral; } function createNewParameters(functionDeclaration: ValidFunctionDeclaration, program: Program, host: LanguageServiceHost): NodeArray { @@ -181,6 +195,12 @@ namespace ts.refactor.convertToNamedParameters { /*propertyName*/ undefined, getParameterName(paramDecl), isRestParameter(paramDecl) ? createArrayLiteral() : paramDecl.initializer); + + suppressLeadingAndTrailingTrivia(element); + if (paramDecl.initializer && element.initializer) { + copyComments(paramDecl.initializer, element.initializer); + } + return element; }); const paramName = createObjectBindingPattern(bindingElements); const paramType = createParamTypeNode(refactorableParameters); @@ -200,13 +220,29 @@ namespace ts.refactor.convertToNamedParameters { objectInitializer); if (hasThisParameter(functionDeclaration.parameters)) { - return createNodeArray([functionDeclaration.parameters[0], newParameter]); + const thisParam = functionDeclaration.parameters[0]; + const newThis = createParameter( + /*decorators*/ undefined, + /*modifiers*/ undefined, + /*dotDotDotToken*/ undefined, + thisParam.name, + /*questionToken*/ undefined, + thisParam.type); + + suppressLeadingAndTrailingTrivia(newThis.name); + copyComments(thisParam.name, newThis.name); + if (thisParam.type && newThis.type) { + suppressLeadingAndTrailingTrivia(newThis.type); + copyComments(thisParam.type, newThis.type); + } + + return createNodeArray([newThis, newParameter]); } return createNodeArray([newParameter]); function createParamTypeNode(parameters: NodeArray): TypeLiteralNode { const members = map(parameters, createPropertySignatureFromParameterDeclaration); - const typeNode = addEmitFlags(createTypeLiteralNode(members), EmitFlags.SingleLine); + const typeNode = addEmitFlags(createTypeLiteralNode(members), EmitFlags.SingleLine); // TODO: add single line option to createTypeLiteralNode return typeNode; } @@ -216,12 +252,20 @@ namespace ts.refactor.convertToNamedParameters { paramType = getTypeNode(paramDeclaration); } - return createPropertySignature( + const propertySignature = createPropertySignature( /*modifiers*/ undefined, getParameterName(paramDeclaration), paramDeclaration.initializer || isRestParameter(paramDeclaration) ? createToken(SyntaxKind.QuestionToken) : paramDeclaration.questionToken, paramType, /*initializer*/ undefined); + + suppressLeadingAndTrailingTrivia(propertySignature); + copyComments(paramDeclaration.name, propertySignature.name); + if (paramDeclaration.type && propertySignature.type) { + copyComments(paramDeclaration.type, propertySignature.type); + } + + return propertySignature; } function getTypeNode(node: Node): TypeNode | undefined { @@ -231,6 +275,27 @@ namespace ts.refactor.convertToNamedParameters { } } + function copyComments(sourceNode: Node, targetNode: Node) { + const sourceFile = sourceNode.getSourceFile(); + const text = sourceFile.text; + if (hasLeadingLineBreak(sourceNode, text)) { + copyLeadingComments(sourceNode, targetNode, sourceFile); + } + else { + copyTrailingAsLeadingComments(sourceNode, targetNode, sourceFile); + } + copyTrailingComments(sourceNode, targetNode, sourceFile); + + function hasLeadingLineBreak(node: Node, text: string) { + const start = node.getFullStart(); + const end = node.getStart(); + for (let i = start; i < end; i++) { + if (text.charCodeAt(i) === CharacterCodes.lineFeed) return true; + } + return false; + } + } + function getParameterName(paramDeclaration: ValidParameterDeclaration) { return getTextOfIdentifierOrLiteral(paramDeclaration.name); } From 4e135f13b5efb89217a06a53cca5f81362630485 Mon Sep 17 00:00:00 2001 From: Gabriela Araujo Britto Date: Mon, 11 Feb 2019 12:03:09 -0800 Subject: [PATCH 052/149] add tests for comments --- .../refactorConvertToNamedParameters25.ts | 15 ++++++++++++ .../refactorConvertToNamedParameters26.ts | 23 +++++++++++++++++++ .../refactorConvertToNamedParameters27.ts | 17 ++++++++++++++ .../refactorConvertToNamedParameters28.ts | 12 ++++++++++ .../refactorConvertToNamedParameters29.ts | 13 +++++++++++ 5 files changed, 80 insertions(+) create mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters25.ts create mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters26.ts create mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters27.ts create mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters28.ts create mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters29.ts diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters25.ts b/tests/cases/fourslash/refactorConvertToNamedParameters25.ts new file mode 100644 index 00000000000..1b51102f80e --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToNamedParameters25.ts @@ -0,0 +1,15 @@ +/// + +////function /*a*/foo/*b*/(a: number, b: number) { /** missing */ +//// return a + b; +////} + +goTo.select("a", "b"); +edit.applyRefactor({ + refactorName: "Convert to named parameters", + actionName: "Convert to named parameters", + actionDescription: "Convert to named parameters", + newContent: `function foo({ a, b }: { a: number; b: number; }) { /** missing */ + return a + b; +}` +}); \ No newline at end of file diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters26.ts b/tests/cases/fourslash/refactorConvertToNamedParameters26.ts new file mode 100644 index 00000000000..20238ac81de --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToNamedParameters26.ts @@ -0,0 +1,23 @@ +/// + +////foo(1, 2); /**a*/ +/////**b*/ function /*a*/foo/*b*/(/**this1*/ this /**this2*/: /**void1*/ void /**void2*/, /**c*/ a /**d*/: /**e*/ number /**f*/, /**g*/ b /**h*/: /**i*/ number /**j*/ = /**k*/ 1 /**l*/) { +//// // m +//// /**n*/ return a + b; // o +//// // p +////} // q +/////**r*/ foo(1); + +goTo.select("a", "b"); +edit.applyRefactor({ + refactorName: "Convert to named parameters", + actionName: "Convert to named parameters", + actionDescription: "Convert to named parameters", + newContent: `foo({ a: 1, b: 2 }); /**a*/ +/**b*/ function foo(/**this1*/ this /**this2*/: /**void1*/ void /**void2*/, { a, b = /**k*/ 1 /**l*/ }: { /**c*/ a /**d*/: /**e*/ number /**f*/; /**g*/ b /**h*/?: /**i*/ number /**j*/; }) { + // m + /**n*/ return a + b; // o + // p +} // q +/**r*/ foo({ a: 1 });` +}); \ No newline at end of file diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters27.ts b/tests/cases/fourslash/refactorConvertToNamedParameters27.ts new file mode 100644 index 00000000000..5bcda77fe0b --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToNamedParameters27.ts @@ -0,0 +1,17 @@ +/// + +////function /*a*/foo/*b*/(a: number, b: number, ...rest: number[]) { +//// return a + b; +////} +////foo(/**a*/ 1 /**b*/, /**c*/ 2 /**d*/, /**e*/ 3 /**f*/, /**g*/ 4 /**h*/); + +goTo.select("a", "b"); +edit.applyRefactor({ + refactorName: "Convert to named parameters", + actionName: "Convert to named parameters", + actionDescription: "Convert to named parameters", + newContent: `function foo({ a, b, rest = [] }: { a: number; b: number; rest?: number[]; }) { + return a + b; +} +foo({ a: /**a*/ 1 /**b*/, b: /**c*/ 2 /**d*/, rest: [/**e*/ 3 /**f*/, /**g*/ 4 /**h*/] });` +}); \ No newline at end of file diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters28.ts b/tests/cases/fourslash/refactorConvertToNamedParameters28.ts new file mode 100644 index 00000000000..8218ac65d80 --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToNamedParameters28.ts @@ -0,0 +1,12 @@ +/// + +////function /*a*/foo/*b*/(// comment +//// /** other comment */ a: number, b: number) { } + +goTo.select("a", "b"); +edit.applyRefactor({ + refactorName: "Convert to named parameters", + actionName: "Convert to named parameters", + actionDescription: "Convert to named parameters", + newContent: `function foo(// comment { a, b }: { /** other comment */ a: number; b: number; }) { }` +}); \ No newline at end of file diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters29.ts b/tests/cases/fourslash/refactorConvertToNamedParameters29.ts new file mode 100644 index 00000000000..02582785944 --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToNamedParameters29.ts @@ -0,0 +1,13 @@ +/// + +////function /*a*/foo/*b*/(// comment +//// a: number, b: number) { } + +goTo.select("a", "b"); +edit.applyRefactor({ + refactorName: "Convert to named parameters", + actionName: "Convert to named parameters", + actionDescription: "Convert to named parameters", + newContent: `function foo(// comment + { a, b }: { a: number; b: number }) { }` +}); \ No newline at end of file From dbd84996aa749712fdd2ea8b4323be71d743c51d Mon Sep 17 00:00:00 2001 From: Gabriela Araujo Britto Date: Mon, 11 Feb 2019 14:24:05 -0800 Subject: [PATCH 053/149] don't apply refactor when parameter has decorators --- src/services/refactors/convertToNamedParameters.ts | 3 ++- .../fourslash/refactorConvertToNamedParameters30.ts | 11 +++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) create mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters30.ts diff --git a/src/services/refactors/convertToNamedParameters.ts b/src/services/refactors/convertToNamedParameters.ts index 41c9935deb6..bf11c5df8b7 100644 --- a/src/services/refactors/convertToNamedParameters.ts +++ b/src/services/refactors/convertToNamedParameters.ts @@ -142,7 +142,7 @@ namespace ts.refactor.convertToNamedParameters { } function isValidParameterDeclaration(paramDeclaration: ParameterDeclaration): paramDeclaration is ValidParameterDeclaration { - return !paramDeclaration.modifiers && isIdentifier(paramDeclaration.name); + return !paramDeclaration.modifiers && !paramDeclaration.decorators && isIdentifier(paramDeclaration.name); } } @@ -361,5 +361,6 @@ namespace ts.refactor.convertToNamedParameters { interface ValidParameterDeclaration extends ParameterDeclaration { name: Identifier; modifiers: undefined; + decorators: undefined; } } \ No newline at end of file diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters30.ts b/tests/cases/fourslash/refactorConvertToNamedParameters30.ts new file mode 100644 index 00000000000..180798af95d --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToNamedParameters30.ts @@ -0,0 +1,11 @@ +/// + +////declare function required(target: Object, propertyKey: string | symbol, parameterIndex: number) +////class C { +//// /*a*/bar/*b*/(@required a: number, b: number) { +//// +//// } +////} + +goTo.select("a", "b"); +verify.not.refactorAvailable("Convert to named parameters"); \ No newline at end of file From 6d2b738bd844ac73b57b6577912b146f1e4f3ef5 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Tue, 12 Feb 2019 17:55:19 -0800 Subject: [PATCH 054/149] Use built local on CI and not LKG (#29886) * Use built local on CI and not LKG * Adjust function to remove need for assertions * Accept baseline diff to go back to local based baseline * Remove comment --- Jakefile.js | 2 +- src/compiler/core.ts | 7 ++++--- tests/baselines/reference/api/tsserverlibrary.d.ts | 2 +- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/Jakefile.js b/Jakefile.js index c6b1cde9d4e..18f4aa56f8d 100644 --- a/Jakefile.js +++ b/Jakefile.js @@ -24,7 +24,7 @@ const host = process.env.TYPESCRIPT_HOST || process.env.host || "node"; const defaultTestTimeout = 40000; const useBuilt = - process.env.USE_BUILT === "true" ? true : + (process.env.USE_BUILT === "true" || process.env.CI === "true") ? true : process.env.LKG === "true" ? false : false; diff --git a/src/compiler/core.ts b/src/compiler/core.ts index c5505ec3736..4bd4801ce8f 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -1396,9 +1396,10 @@ namespace ts { export function assign(t: T, ...args: (T | undefined)[]) { for (const arg of args) { - for (const p in arg!) { - if (hasProperty(arg!, p)) { - t![p] = arg![p]; // TODO: GH#23368 + if (arg === undefined) continue; + for (const p in arg) { + if (hasProperty(arg, p)) { + t[p] = arg[p]; } } } diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 36c246c999f..70fccdf87c1 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -8347,7 +8347,7 @@ declare namespace ts.server { excludedFiles: ReadonlyArray; private typeAcquisition; updateGraph(): boolean; - getExcludedFiles(): ReadonlyArray; + getExcludedFiles(): readonly NormalizedPath[]; getTypeAcquisition(): TypeAcquisition; setTypeAcquisition(newTypeAcquisition: TypeAcquisition): void; } From 950861ec7f314db7092f71eab815c248fe5dc5b8 Mon Sep 17 00:00:00 2001 From: Titian Cernicova-Dragomir Date: Wed, 13 Feb 2019 17:25:23 +0200 Subject: [PATCH 055/149] Improve error message for using value as type. --- src/compiler/checker.ts | 14 +++++++++++++- src/compiler/diagnosticMessages.json | 4 ++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 9021a50ef8d..a1248d536a8 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -1518,7 +1518,8 @@ namespace ts { !checkAndReportErrorForExtendingInterface(errorLocation) && !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && - !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning)) { + !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) && + !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) { let suggestion: Symbol | undefined; if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning); @@ -1708,6 +1709,17 @@ namespace ts { return false; } + function checkAndReportErrorForUsingValueAsType(errorLocation: Node, name: __String, meaning: SymbolFlags): boolean { + if (meaning & (SymbolFlags.Type & ~SymbolFlags.Namespace)) { + const symbol = resolveSymbol(resolveName(errorLocation, name, ~SymbolFlags.Type & SymbolFlags.Value, /*nameNotFoundMessage*/undefined, /*nameArg*/ undefined, /*isUse*/ false)); + if (symbol && !(symbol.flags & SymbolFlags.Namespace)) { + error(errorLocation, Diagnostics._0_refers_to_a_value_but_is_being_used_as_a_type_here, unescapeLeadingUnderscores(name)); + return true; + } + } + return false; + } + function checkAndReportErrorForUsingTypeAsValue(errorLocation: Node, name: __String, meaning: SymbolFlags): boolean { if (meaning & (SymbolFlags.Value & ~SymbolFlags.NamespaceModule)) { if (name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never") { diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index e40fccd8bf2..89794d26181 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -2581,6 +2581,10 @@ "category": "Error", "code": 2748 }, + "'{0}' refers to a value, but is being used as a type here.": { + "category": "Error", + "code": 2749 + }, "Import declaration '{0}' is using private name '{1}'.": { "category": "Error", From e1855740961320eda7fa79e45b7ec4bad73c6aab Mon Sep 17 00:00:00 2001 From: Titian Cernicova-Dragomir Date: Wed, 13 Feb 2019 17:39:06 +0200 Subject: [PATCH 056/149] Accept new baseline for Improve error message for using value as type. --- ...owImportClausesToMergeWithTypes.errors.txt | 4 ++-- .../reference/callOverloads3.errors.txt | 8 ++++---- .../reference/callOverloads4.errors.txt | 8 ++++---- .../reference/callOverloads5.errors.txt | 8 ++++---- .../constructorOverloads7.errors.txt | 8 ++++---- .../baselines/reference/intrinsics.errors.txt | 4 ++-- ...eNongenericInstantiationAttempt.errors.txt | 4 ++-- ...serAmbiguityWithBinaryOperator4.errors.txt | 8 ++++---- .../reference/typeAssertions.errors.txt | 8 ++++---- .../typeGuardFunctionErrors.errors.txt | 20 +++++++++---------- 10 files changed, 40 insertions(+), 40 deletions(-) diff --git a/tests/baselines/reference/allowImportClausesToMergeWithTypes.errors.txt b/tests/baselines/reference/allowImportClausesToMergeWithTypes.errors.txt index 684921ae126..8c4f9955310 100644 --- a/tests/baselines/reference/allowImportClausesToMergeWithTypes.errors.txt +++ b/tests/baselines/reference/allowImportClausesToMergeWithTypes.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/index.ts(4,1): error TS2693: 'zzz' only refers to a type, but is being used as a value here. -tests/cases/compiler/index.ts(9,10): error TS2304: Cannot find name 'originalZZZ'. +tests/cases/compiler/index.ts(9,10): error TS2749: 'originalZZZ' refers to a value, but is being used as a type here. ==== tests/cases/compiler/b.ts (0 errors) ==== @@ -31,4 +31,4 @@ tests/cases/compiler/index.ts(9,10): error TS2304: Cannot find name 'originalZZZ const y: originalZZZ = x; ~~~~~~~~~~~ -!!! error TS2304: Cannot find name 'originalZZZ'. \ No newline at end of file +!!! error TS2749: 'originalZZZ' refers to a value, but is being used as a type here. \ No newline at end of file diff --git a/tests/baselines/reference/callOverloads3.errors.txt b/tests/baselines/reference/callOverloads3.errors.txt index 9b14a6791a3..7a38d132cbb 100644 --- a/tests/baselines/reference/callOverloads3.errors.txt +++ b/tests/baselines/reference/callOverloads3.errors.txt @@ -1,8 +1,8 @@ tests/cases/compiler/callOverloads3.ts(1,10): error TS2300: Duplicate identifier 'Foo'. -tests/cases/compiler/callOverloads3.ts(1,16): error TS2304: Cannot find name 'Foo'. +tests/cases/compiler/callOverloads3.ts(1,16): error TS2749: 'Foo' refers to a value, but is being used as a type here. tests/cases/compiler/callOverloads3.ts(2,10): error TS2300: Duplicate identifier 'Foo'. tests/cases/compiler/callOverloads3.ts(2,10): error TS2391: Function implementation is missing or not immediately following the declaration. -tests/cases/compiler/callOverloads3.ts(2,24): error TS2304: Cannot find name 'Foo'. +tests/cases/compiler/callOverloads3.ts(2,24): error TS2749: 'Foo' refers to a value, but is being used as a type here. tests/cases/compiler/callOverloads3.ts(3,7): error TS2300: Duplicate identifier 'Foo'. tests/cases/compiler/callOverloads3.ts(11,10): error TS2350: Only a void function can be called with the 'new' keyword. @@ -12,14 +12,14 @@ tests/cases/compiler/callOverloads3.ts(11,10): error TS2350: Only a void functio ~~~ !!! error TS2300: Duplicate identifier 'Foo'. ~~~ -!!! error TS2304: Cannot find name 'Foo'. +!!! error TS2749: 'Foo' refers to a value, but is being used as a type here. function Foo(s:string):Foo; // error ~~~ !!! error TS2300: Duplicate identifier 'Foo'. ~~~ !!! error TS2391: Function implementation is missing or not immediately following the declaration. ~~~ -!!! error TS2304: Cannot find name 'Foo'. +!!! error TS2749: 'Foo' refers to a value, but is being used as a type here. class Foo { // error ~~~ !!! error TS2300: Duplicate identifier 'Foo'. diff --git a/tests/baselines/reference/callOverloads4.errors.txt b/tests/baselines/reference/callOverloads4.errors.txt index 04ac340c990..dcecd65666e 100644 --- a/tests/baselines/reference/callOverloads4.errors.txt +++ b/tests/baselines/reference/callOverloads4.errors.txt @@ -1,8 +1,8 @@ tests/cases/compiler/callOverloads4.ts(1,10): error TS2300: Duplicate identifier 'Foo'. -tests/cases/compiler/callOverloads4.ts(1,16): error TS2304: Cannot find name 'Foo'. +tests/cases/compiler/callOverloads4.ts(1,16): error TS2749: 'Foo' refers to a value, but is being used as a type here. tests/cases/compiler/callOverloads4.ts(2,10): error TS2300: Duplicate identifier 'Foo'. tests/cases/compiler/callOverloads4.ts(2,10): error TS2391: Function implementation is missing or not immediately following the declaration. -tests/cases/compiler/callOverloads4.ts(2,24): error TS2304: Cannot find name 'Foo'. +tests/cases/compiler/callOverloads4.ts(2,24): error TS2749: 'Foo' refers to a value, but is being used as a type here. tests/cases/compiler/callOverloads4.ts(3,7): error TS2300: Duplicate identifier 'Foo'. tests/cases/compiler/callOverloads4.ts(11,10): error TS2350: Only a void function can be called with the 'new' keyword. @@ -12,14 +12,14 @@ tests/cases/compiler/callOverloads4.ts(11,10): error TS2350: Only a void functio ~~~ !!! error TS2300: Duplicate identifier 'Foo'. ~~~ -!!! error TS2304: Cannot find name 'Foo'. +!!! error TS2749: 'Foo' refers to a value, but is being used as a type here. function Foo(s:string):Foo; // error ~~~ !!! error TS2300: Duplicate identifier 'Foo'. ~~~ !!! error TS2391: Function implementation is missing or not immediately following the declaration. ~~~ -!!! error TS2304: Cannot find name 'Foo'. +!!! error TS2749: 'Foo' refers to a value, but is being used as a type here. class Foo { // error ~~~ !!! error TS2300: Duplicate identifier 'Foo'. diff --git a/tests/baselines/reference/callOverloads5.errors.txt b/tests/baselines/reference/callOverloads5.errors.txt index e521a9a9076..e9ebdc8a524 100644 --- a/tests/baselines/reference/callOverloads5.errors.txt +++ b/tests/baselines/reference/callOverloads5.errors.txt @@ -1,8 +1,8 @@ tests/cases/compiler/callOverloads5.ts(1,10): error TS2300: Duplicate identifier 'Foo'. -tests/cases/compiler/callOverloads5.ts(1,16): error TS2304: Cannot find name 'Foo'. +tests/cases/compiler/callOverloads5.ts(1,16): error TS2749: 'Foo' refers to a value, but is being used as a type here. tests/cases/compiler/callOverloads5.ts(2,10): error TS2300: Duplicate identifier 'Foo'. tests/cases/compiler/callOverloads5.ts(2,10): error TS2391: Function implementation is missing or not immediately following the declaration. -tests/cases/compiler/callOverloads5.ts(2,24): error TS2304: Cannot find name 'Foo'. +tests/cases/compiler/callOverloads5.ts(2,24): error TS2749: 'Foo' refers to a value, but is being used as a type here. tests/cases/compiler/callOverloads5.ts(3,7): error TS2300: Duplicate identifier 'Foo'. tests/cases/compiler/callOverloads5.ts(13,10): error TS2350: Only a void function can be called with the 'new' keyword. @@ -12,14 +12,14 @@ tests/cases/compiler/callOverloads5.ts(13,10): error TS2350: Only a void functio ~~~ !!! error TS2300: Duplicate identifier 'Foo'. ~~~ -!!! error TS2304: Cannot find name 'Foo'. +!!! error TS2749: 'Foo' refers to a value, but is being used as a type here. function Foo(s:string):Foo; // error ~~~ !!! error TS2300: Duplicate identifier 'Foo'. ~~~ !!! error TS2391: Function implementation is missing or not immediately following the declaration. ~~~ -!!! error TS2304: Cannot find name 'Foo'. +!!! error TS2749: 'Foo' refers to a value, but is being used as a type here. class Foo { // error ~~~ !!! error TS2300: Duplicate identifier 'Foo'. diff --git a/tests/baselines/reference/constructorOverloads7.errors.txt b/tests/baselines/reference/constructorOverloads7.errors.txt index c915b8f9754..81aeaaf24ff 100644 --- a/tests/baselines/reference/constructorOverloads7.errors.txt +++ b/tests/baselines/reference/constructorOverloads7.errors.txt @@ -1,6 +1,6 @@ tests/cases/compiler/constructorOverloads7.ts(1,15): error TS2300: Duplicate identifier 'Point'. -tests/cases/compiler/constructorOverloads7.ts(7,35): error TS2304: Cannot find name 'Point'. -tests/cases/compiler/constructorOverloads7.ts(8,14): error TS2304: Cannot find name 'Point'. +tests/cases/compiler/constructorOverloads7.ts(7,35): error TS2749: 'Point' refers to a value, but is being used as a type here. +tests/cases/compiler/constructorOverloads7.ts(8,14): error TS2749: 'Point' refers to a value, but is being used as a type here. tests/cases/compiler/constructorOverloads7.ts(15,10): error TS2300: Duplicate identifier 'Point'. tests/cases/compiler/constructorOverloads7.ts(22,18): error TS2384: Overload signatures must all be ambient or non-ambient. @@ -16,10 +16,10 @@ tests/cases/compiler/constructorOverloads7.ts(22,18): error TS2384: Overload sig add(dx: number, dy: number): Point; ~~~~~ -!!! error TS2304: Cannot find name 'Point'. +!!! error TS2749: 'Point' refers to a value, but is being used as a type here. origin: Point; ~~~~~ -!!! error TS2304: Cannot find name 'Point'. +!!! error TS2749: 'Point' refers to a value, but is being used as a type here. } diff --git a/tests/baselines/reference/intrinsics.errors.txt b/tests/baselines/reference/intrinsics.errors.txt index 5692f057903..13d61dacbcf 100644 --- a/tests/baselines/reference/intrinsics.errors.txt +++ b/tests/baselines/reference/intrinsics.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/intrinsics.ts(1,21): error TS2304: Cannot find name 'hasOwnProperty'. +tests/cases/compiler/intrinsics.ts(1,21): error TS2749: 'hasOwnProperty' refers to a value, but is being used as a type here. tests/cases/compiler/intrinsics.ts(1,21): error TS4025: Exported variable 'hasOwnProperty' has or is using private name 'hasOwnProperty'. tests/cases/compiler/intrinsics.ts(10,1): error TS2304: Cannot find name '__proto__'. @@ -6,7 +6,7 @@ tests/cases/compiler/intrinsics.ts(10,1): error TS2304: Cannot find name '__prot ==== tests/cases/compiler/intrinsics.ts (3 errors) ==== var hasOwnProperty: hasOwnProperty; // Error ~~~~~~~~~~~~~~ -!!! error TS2304: Cannot find name 'hasOwnProperty'. +!!! error TS2749: 'hasOwnProperty' refers to a value, but is being used as a type here. ~~~~~~~~~~~~~~ !!! error TS4025: Exported variable 'hasOwnProperty' has or is using private name 'hasOwnProperty'. diff --git a/tests/baselines/reference/jsdocTypeNongenericInstantiationAttempt.errors.txt b/tests/baselines/reference/jsdocTypeNongenericInstantiationAttempt.errors.txt index 941e4386f99..b3298f137f1 100644 --- a/tests/baselines/reference/jsdocTypeNongenericInstantiationAttempt.errors.txt +++ b/tests/baselines/reference/jsdocTypeNongenericInstantiationAttempt.errors.txt @@ -5,7 +5,7 @@ tests/cases/compiler/index4.js(2,19): error TS2315: Type 'Function' is not gener tests/cases/compiler/index5.js(2,19): error TS2315: Type 'String' is not generic. tests/cases/compiler/index6.js(2,19): error TS2315: Type 'Number' is not generic. tests/cases/compiler/index7.js(2,19): error TS2315: Type 'Object' is not generic. -tests/cases/compiler/index8.js(4,12): error TS2304: Cannot find name 'fn'. +tests/cases/compiler/index8.js(4,12): error TS2749: 'fn' refers to a value, but is being used as a type here. tests/cases/compiler/index8.js(4,15): error TS2304: Cannot find name 'T'. @@ -90,7 +90,7 @@ tests/cases/compiler/index8.js(4,15): error TS2304: Cannot find name 'T'. /** * @param {fn} somebody ~~ -!!! error TS2304: Cannot find name 'fn'. +!!! error TS2749: 'fn' refers to a value, but is being used as a type here. ~ !!! error TS2304: Cannot find name 'T'. */ diff --git a/tests/baselines/reference/parserAmbiguityWithBinaryOperator4.errors.txt b/tests/baselines/reference/parserAmbiguityWithBinaryOperator4.errors.txt index 41147305ce0..a94b60e5f99 100644 --- a/tests/baselines/reference/parserAmbiguityWithBinaryOperator4.errors.txt +++ b/tests/baselines/reference/parserAmbiguityWithBinaryOperator4.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/parser/ecmascript5/Generics/parserAmbiguityWithBinaryOperator4.ts(3,9): error TS2347: Untyped function calls may not accept type arguments. -tests/cases/conformance/parser/ecmascript5/Generics/parserAmbiguityWithBinaryOperator4.ts(3,11): error TS2304: Cannot find name 'b'. -tests/cases/conformance/parser/ecmascript5/Generics/parserAmbiguityWithBinaryOperator4.ts(3,14): error TS2304: Cannot find name 'b'. +tests/cases/conformance/parser/ecmascript5/Generics/parserAmbiguityWithBinaryOperator4.ts(3,11): error TS2749: 'b' refers to a value, but is being used as a type here. +tests/cases/conformance/parser/ecmascript5/Generics/parserAmbiguityWithBinaryOperator4.ts(3,14): error TS2749: 'b' refers to a value, but is being used as a type here. ==== tests/cases/conformance/parser/ecmascript5/Generics/parserAmbiguityWithBinaryOperator4.ts (3 errors) ==== @@ -10,7 +10,7 @@ tests/cases/conformance/parser/ecmascript5/Generics/parserAmbiguityWithBinaryOpe ~~~~~~~~~~~~~~ !!! error TS2347: Untyped function calls may not accept type arguments. ~ -!!! error TS2304: Cannot find name 'b'. +!!! error TS2749: 'b' refers to a value, but is being used as a type here. ~ -!!! error TS2304: Cannot find name 'b'. +!!! error TS2749: 'b' refers to a value, but is being used as a type here. } \ No newline at end of file diff --git a/tests/baselines/reference/typeAssertions.errors.txt b/tests/baselines/reference/typeAssertions.errors.txt index 27de59a7645..ef9a23b8d8a 100644 --- a/tests/baselines/reference/typeAssertions.errors.txt +++ b/tests/baselines/reference/typeAssertions.errors.txt @@ -7,7 +7,7 @@ tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(37,13): err Property 'q' is missing in type 'SomeDerived' but required in type 'SomeOther'. tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(38,13): error TS2352: Conversion of type 'SomeBase' to type 'SomeOther' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. Property 'q' is missing in type 'SomeBase' but required in type 'SomeOther'. -tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(44,5): error TS2304: Cannot find name 'numOrStr'. +tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(44,5): error TS2749: 'numOrStr' refers to a value, but is being used as a type here. tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(44,14): error TS1005: '>' expected. tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(44,14): error TS2304: Cannot find name 'is'. tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(44,17): error TS1005: ')' expected. @@ -15,7 +15,7 @@ tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(44,17): err tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(44,48): error TS1005: ';' expected. tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(45,2): error TS2322: Type 'string | number' is not assignable to type 'string'. Type 'number' is not assignable to type 'string'. -tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(48,32): error TS2304: Cannot find name 'numOrStr'. +tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(48,32): error TS2749: 'numOrStr' refers to a value, but is being used as a type here. tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(48,41): error TS1005: ')' expected. tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(48,41): error TS2304: Cannot find name 'is'. tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(48,44): error TS1005: ';' expected. @@ -86,7 +86,7 @@ tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(48,50): err var str: string; if((numOrStr === undefined)) { // Error ~~~~~~~~ -!!! error TS2304: Cannot find name 'numOrStr'. +!!! error TS2749: 'numOrStr' refers to a value, but is being used as a type here. ~~ !!! error TS1005: '>' expected. ~~ @@ -105,7 +105,7 @@ tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts(48,50): err if((numOrStr === undefined) as numOrStr is string) { // Error ~~~~~~~~ -!!! error TS2304: Cannot find name 'numOrStr'. +!!! error TS2749: 'numOrStr' refers to a value, but is being used as a type here. ~~ !!! error TS1005: ')' expected. ~~ diff --git a/tests/baselines/reference/typeGuardFunctionErrors.errors.txt b/tests/baselines/reference/typeGuardFunctionErrors.errors.txt index a6ea9961c54..6f24585a85f 100644 --- a/tests/baselines/reference/typeGuardFunctionErrors.errors.txt +++ b/tests/baselines/reference/typeGuardFunctionErrors.errors.txt @@ -1,10 +1,10 @@ tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(1,7): error TS2300: Duplicate identifier 'A'. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(14,5): error TS2322: Type '""' is not assignable to type 'boolean'. -tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(17,55): error TS2304: Cannot find name 'x'. +tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(17,55): error TS2749: 'x' refers to a value, but is being used as a type here. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(17,57): error TS1144: '{' or ';' expected. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(17,60): error TS1005: ';' expected. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(17,62): error TS1005: ';' expected. -tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(21,33): error TS2304: Cannot find name 'x'. +tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(21,33): error TS2749: 'x' refers to a value, but is being used as a type here. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(25,33): error TS1225: Cannot find parameter 'x'. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(29,10): error TS2391: Function implementation is missing or not immediately following the declaration. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(30,5): error TS1131: Property or signature expected. @@ -28,14 +28,14 @@ tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(84,1): Type predicate 'p2 is A' is not assignable to 'p1 is A'. Parameter 'p2' is not in the same position as parameter 'p1'. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(90,1): error TS2322: Type '(p1: any, p2: any, p3: any) => p1 is A' is not assignable to type '(p1: any, p2: any) => p1 is A'. -tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(95,9): error TS2304: Cannot find name 'b'. +tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(95,9): error TS2749: 'b' refers to a value, but is being used as a type here. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(95,11): error TS1005: ',' expected. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(95,14): error TS1005: ',' expected. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(95,14): error TS2300: Duplicate identifier 'A'. -tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(96,16): error TS2304: Cannot find name 'b'. +tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(96,16): error TS2749: 'b' refers to a value, but is being used as a type here. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(96,18): error TS1005: ',' expected. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(96,21): error TS1005: ',' expected. -tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(97,20): error TS2304: Cannot find name 'b'. +tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(97,20): error TS2749: 'b' refers to a value, but is being used as a type here. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(97,22): error TS1144: '{' or ';' expected. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(97,25): error TS1005: ';' expected. tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(97,27): error TS1005: ';' expected. @@ -91,7 +91,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(166,54 function hasTypeGuardTypeInsideTypeGuardType(x): x is x is A { ~ -!!! error TS2304: Cannot find name 'x'. +!!! error TS2749: 'x' refers to a value, but is being used as a type here. ~~ !!! error TS1144: '{' or ';' expected. ~ @@ -103,7 +103,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(166,54 function hasMissingIsKeyword(): x { ~ -!!! error TS2304: Cannot find name 'x'. +!!! error TS2749: 'x' refers to a value, but is being used as a type here. return true; } @@ -222,7 +222,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(166,54 // Type predicates in non-return type positions var b1: b is A; ~ -!!! error TS2304: Cannot find name 'b'. +!!! error TS2749: 'b' refers to a value, but is being used as a type here. ~~ !!! error TS1005: ',' expected. ~ @@ -231,14 +231,14 @@ tests/cases/conformance/expressions/typeGuards/typeGuardFunctionErrors.ts(166,54 !!! error TS2300: Duplicate identifier 'A'. function b2(a: b is A) {}; ~ -!!! error TS2304: Cannot find name 'b'. +!!! error TS2749: 'b' refers to a value, but is being used as a type here. ~~ !!! error TS1005: ',' expected. ~ !!! error TS1005: ',' expected. function b3(): A | b is A { ~ -!!! error TS2304: Cannot find name 'b'. +!!! error TS2749: 'b' refers to a value, but is being used as a type here. ~~ !!! error TS1144: '{' or ';' expected. ~ From ef4db31e84aa9dbf0a43cc7a1230f3aeb4797f6c Mon Sep 17 00:00:00 2001 From: Gabriela Araujo Britto Date: Wed, 13 Feb 2019 11:35:44 -0800 Subject: [PATCH 057/149] don't apply changes when unexpected reference is found --- .../refactors/convertToNamedParameters.ts | 79 +++++++++++++++---- 1 file changed, 63 insertions(+), 16 deletions(-) diff --git a/src/services/refactors/convertToNamedParameters.ts b/src/services/refactors/convertToNamedParameters.ts index bf11c5df8b7..5207c9a1b45 100644 --- a/src/services/refactors/convertToNamedParameters.ts +++ b/src/services/refactors/convertToNamedParameters.ts @@ -11,8 +11,8 @@ namespace ts.refactor.convertToNamedParameters { function getAvailableActions(context: RefactorContext): ReadonlyArray { const { file, startPosition } = context; - const func = getFunctionDeclarationAtPosition(file, startPosition, context.program.getTypeChecker()); - if (!func) return emptyArray; + const functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, context.program.getTypeChecker()); + if (!functionDeclaration) return emptyArray; return [{ name: refactorName, @@ -31,7 +31,7 @@ namespace ts.refactor.convertToNamedParameters { if (!functionDeclaration || !cancellationToken) return undefined; const edits = textChanges.ChangeTracker.with(context, t => doChange(file, program, cancellationToken, host, t, functionDeclaration)); - return refactorSucceeded ? { renameFilename: undefined, renameLocation: undefined, edits } : undefined; + return { renameFilename: undefined, renameLocation: undefined, edits: refactorSucceeded ? edits : [] }; } function doChange(sourceFile: SourceFile, program: Program, cancellationToken: CancellationToken, host: LanguageServiceHost, changes: textChanges.ChangeTracker, functionDeclaration: ValidFunctionDeclaration): void { @@ -42,8 +42,9 @@ namespace ts.refactor.convertToNamedParameters { const functionNames = getFunctionDeclarationNames(functionDeclaration); const functionRefs = flatMap(functionNames, name => FindAllReferences.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken)); - const functionCalls = deduplicate(getDirectFunctionCalls(functionRefs), (a, b) => a === b); - refactorSucceeded = true; // TODO: check if a bad reference was found + const groupedRefs = groupReferences(functionNames, functionRefs); + checkReferences(functionNames, groupedRefs); + const functionCalls = groupedRefs.calls; forEach(functionCalls, call => { if (call.arguments && call.arguments.length) { @@ -66,9 +67,37 @@ namespace ts.refactor.convertToNamedParameters { return updateNode(newDeclaration, declaration); } - function getDirectFunctionCalls(referenceEntries: ReadonlyArray | undefined): ReadonlyArray { - return mapDefined(referenceEntries, (entry) => { - if (entry.kind !== FindAllReferences.EntryKind.Span && entry.node.parent) { + function checkReferences(names: Node[], groupedRefs: GroupedReferences): void { + if (groupedRefs.unhandled.length > 0) { + refactorSucceeded = false; + } + if (groupedRefs.declarations.length > names.length) { + refactorSucceeded = false; + } + } + + function groupReferences(names: Node[], referenceEntries: ReadonlyArray | undefined): GroupedReferences { + const references: GroupedReferences = { calls: [], declarations: [], unhandled: [] }; + forEach(referenceEntries, (entry) => { + const decl = entryToDeclarationName(entry); + if (decl) { + references.declarations.push(decl); + return; + } + const call = entryToFunctionCall(entry); + if (call) { + references.calls.push(call); + return; + } + const node = entryToNode(entry); + if (node) { + references.unhandled.push(node); + } + }); + return references; + + function entryToFunctionCall(entry: FindAllReferences.Entry): CallExpression | NewExpression | undefined { + if (entry.kind !== FindAllReferences.EntryKind.Span && entry.node && entry.node.parent) { const functionRef = entry.node; const parent = functionRef.parent; switch (parent.kind) { @@ -109,7 +138,27 @@ namespace ts.refactor.convertToNamedParameters { } } return undefined; - }); + } + + function entryToDeclarationName(entry: FindAllReferences.Entry): Node | undefined { + if (entry.kind !== FindAllReferences.EntryKind.Span && entry.node && contains(names, entry.node)) { + return entry.node; + } + return undefined; + } + + function entryToNode(entry: FindAllReferences.Entry): Node | undefined { + if (entry.kind !== FindAllReferences.EntryKind.Span && entry.node) { + return entry.node; + } + return undefined; + } + } + + interface GroupedReferences { + calls: (CallExpression | NewExpression)[]; + declarations: Node[]; + unhandled: Node[]; } function getFunctionDeclarationAtPosition(file: SourceFile, startPosition: number, checker: TypeChecker): ValidFunctionDeclaration | undefined { @@ -126,7 +175,7 @@ namespace ts.refactor.convertToNamedParameters { return !!functionDeclaration.name && isPropertyName(functionDeclaration.name) && isValidParameterNodeArray(functionDeclaration.parameters) && !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration); case SyntaxKind.Constructor: if (isClassDeclaration(functionDeclaration.parent)) { - return !!functionDeclaration.parent.name && isValidParameterNodeArray(functionDeclaration.parameters) && !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration); + return isValidParameterNodeArray(functionDeclaration.parameters) && !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration); } else { return isVariableDeclaration(functionDeclaration.parent.parent) && !functionDeclaration.parent.parent.type && isVarConst(functionDeclaration.parent.parent) && isValidParameterNodeArray(functionDeclaration.parameters) && !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration); @@ -310,15 +359,13 @@ namespace ts.refactor.convertToNamedParameters { let name: Node; switch (functionDeclaration.parent.kind) { case SyntaxKind.ClassDeclaration: - name = functionDeclaration.parent.name; - break; + return [ctrKeyword!]; case SyntaxKind.ClassExpression: name = functionDeclaration.parent.parent.name; - break; + if (ctrKeyword) return [ctrKeyword, name]; + return [name]; default: return Debug.assertNever(functionDeclaration.parent); } - if (ctrKeyword) return [ctrKeyword, name]; - return [name]; case SyntaxKind.ArrowFunction: case SyntaxKind.FunctionExpression: return [functionDeclaration.parent.name]; @@ -330,7 +377,7 @@ namespace ts.refactor.convertToNamedParameters { type ValidVariableDeclaration = VariableDeclaration & { type: undefined }; interface ValidConstructor extends ConstructorDeclaration { - parent: (ClassDeclaration & { name: Identifier }) | (ClassExpression & { parent: ValidVariableDeclaration }); + parent: ClassDeclaration | (ClassExpression & { parent: ValidVariableDeclaration }); parameters: NodeArray; body: FunctionBody; } From ec0e734708fd5c601a06e456b9f680103b8c3eb5 Mon Sep 17 00:00:00 2001 From: Gabriela Araujo Britto Date: Wed, 13 Feb 2019 11:36:59 -0800 Subject: [PATCH 058/149] return function expression name in getFunctionDeclarationNames --- src/services/refactors/convertToNamedParameters.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/services/refactors/convertToNamedParameters.ts b/src/services/refactors/convertToNamedParameters.ts index 5207c9a1b45..d5e3a43be29 100644 --- a/src/services/refactors/convertToNamedParameters.ts +++ b/src/services/refactors/convertToNamedParameters.ts @@ -367,7 +367,9 @@ namespace ts.refactor.convertToNamedParameters { default: return Debug.assertNever(functionDeclaration.parent); } case SyntaxKind.ArrowFunction: + return [functionDeclaration.parent.name]; case SyntaxKind.FunctionExpression: + if (functionDeclaration.name) return [functionDeclaration.name, functionDeclaration.parent.name]; return [functionDeclaration.parent.name]; } } From ad7702f15a89d7056459375898fa7bfa5f96e5ef Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Wed, 13 Feb 2019 12:57:35 -0800 Subject: [PATCH 059/149] Disable node 6 (#29832) * Disable node 6 It exits LTS in a couple of months, and doesn't support async/await, meaning that it blocks us from switching Travis to use gulp instead of jake. * Swap in node 8 for node 6 --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 0f720b7375e..b35dabcbb5f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,7 +3,7 @@ language: node_js node_js: - 'node' - '10' - - '6' + - '8' sudo: false From 05e9d6c9ded138b48aeeeb03c3cf2d49c865b48d Mon Sep 17 00:00:00 2001 From: Gabriela Araujo Britto Date: Wed, 13 Feb 2019 15:34:18 -0800 Subject: [PATCH 060/149] fix reference checking --- .../refactors/convertToNamedParameters.ts | 211 +++++++++--------- 1 file changed, 108 insertions(+), 103 deletions(-) diff --git a/src/services/refactors/convertToNamedParameters.ts b/src/services/refactors/convertToNamedParameters.ts index d5e3a43be29..6e5881a31f6 100644 --- a/src/services/refactors/convertToNamedParameters.ts +++ b/src/services/refactors/convertToNamedParameters.ts @@ -5,7 +5,6 @@ namespace ts.refactor.convertToNamedParameters { const actionNameNamedParameters = "Convert to named parameters"; const actionDescriptionNamedParameters = "Convert to named parameters"; const minimumParameterLength = 1; - let refactorSucceeded = true; registerRefactor(refactorName, { getEditsForAction, getAvailableActions }); @@ -30,22 +29,27 @@ namespace ts.refactor.convertToNamedParameters { const functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, program.getTypeChecker()); if (!functionDeclaration || !cancellationToken) return undefined; - const edits = textChanges.ChangeTracker.with(context, t => doChange(file, program, cancellationToken, host, t, functionDeclaration)); - return { renameFilename: undefined, renameLocation: undefined, edits: refactorSucceeded ? edits : [] }; + const functionNames = getFunctionDeclarationNames(functionDeclaration); + const groupedReferences = getGroupedReferences(functionNames, program, cancellationToken); + if (checkReferences(functionNames, groupedReferences)) { + const edits = textChanges.ChangeTracker.with(context, t => doChange(file, program, host, t, functionDeclaration, groupedReferences)); + return { renameFilename: undefined, renameLocation: undefined, edits }; + } + + return { edits: [] }; } - function doChange(sourceFile: SourceFile, program: Program, cancellationToken: CancellationToken, host: LanguageServiceHost, changes: textChanges.ChangeTracker, functionDeclaration: ValidFunctionDeclaration): void { - const newParamDeclaration = map(createNewParameters(functionDeclaration, program, host), param => getSynthesizedDeepClone(param, /*includeTrivia*/ true)); - const newFunctionDeclaration = updateDeclarationParameters(functionDeclaration, createNodeArray(newParamDeclaration)); - suppressLeadingAndTrailingTrivia(newFunctionDeclaration, /*recursive*/ false); - changes.replaceNode(sourceFile, functionDeclaration, newFunctionDeclaration); - const functionNames = getFunctionDeclarationNames(functionDeclaration); - const functionRefs = flatMap(functionNames, name => FindAllReferences.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken)); - const groupedRefs = groupReferences(functionNames, functionRefs); - checkReferences(functionNames, groupedRefs); - const functionCalls = groupedRefs.calls; + function doChange(sourceFile: SourceFile, program: Program, host: LanguageServiceHost, changes: textChanges.ChangeTracker, functionDeclaration: ValidFunctionDeclaration, groupedReferences: GroupedReferences): void { + const newParamDeclaration = map(createNewParameters(functionDeclaration, program, host), param => getSynthesizedDeepClone(param)); + changes.replaceNodeRangeWithNodes( + sourceFile, + first(functionDeclaration.parameters), + last(functionDeclaration.parameters), + newParamDeclaration, + { joiner: ", ", indentation: 0 }); // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter + const functionCalls = groupedReferences.calls; forEach(functionCalls, call => { if (call.arguments && call.arguments.length) { const newArgument = getSynthesizedDeepClone(createNewArguments(functionDeclaration, call.arguments), /*includeTrivia*/ true); @@ -61,104 +65,99 @@ namespace ts.refactor.convertToNamedParameters { return updateNode(newCall, call); } - function updateDeclarationParameters(declaration: SignatureDeclaration, parameters: NodeArray): SignatureDeclaration { - const newDeclaration = getSynthesizedClone(declaration); - newDeclaration.parameters = parameters; - return updateNode(newDeclaration, declaration); - } + function getGroupedReferences(functionNames: Node[], program: Program, cancellationToken: CancellationToken): GroupedReferences { + const functionRefs = flatMap(functionNames, name => FindAllReferences.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken)); + const groupedReferences = groupReferences(functionRefs); + return groupedReferences; - function checkReferences(names: Node[], groupedRefs: GroupedReferences): void { - if (groupedRefs.unhandled.length > 0) { - refactorSucceeded = false; - } - if (groupedRefs.declarations.length > names.length) { - refactorSucceeded = false; - } - } - - function groupReferences(names: Node[], referenceEntries: ReadonlyArray | undefined): GroupedReferences { - const references: GroupedReferences = { calls: [], declarations: [], unhandled: [] }; - forEach(referenceEntries, (entry) => { - const decl = entryToDeclarationName(entry); - if (decl) { - references.declarations.push(decl); - return; - } - const call = entryToFunctionCall(entry); - if (call) { - references.calls.push(call); - return; - } - const node = entryToNode(entry); - if (node) { - references.unhandled.push(node); - } - }); - return references; - - function entryToFunctionCall(entry: FindAllReferences.Entry): CallExpression | NewExpression | undefined { - if (entry.kind !== FindAllReferences.EntryKind.Span && entry.node && entry.node.parent) { - const functionRef = entry.node; - const parent = functionRef.parent; - switch (parent.kind) { - // Function call (foo(...)) - case SyntaxKind.CallExpression: - const callExpression = tryCast(parent, isCallExpression); - if (callExpression && callExpression.expression === functionRef) { - return callExpression; - } - break; - // Constructor call (new Foo(...)) - case SyntaxKind.NewExpression: - const newExpression = tryCast(parent, isNewExpression); - if (newExpression && newExpression.expression === functionRef) { - return newExpression; - } - break; - // Method call (x.foo(...)) - case SyntaxKind.PropertyAccessExpression: - const propertyAccessExpression = tryCast(parent, isPropertyAccessExpression); - if (propertyAccessExpression && propertyAccessExpression.parent && propertyAccessExpression.name === functionRef) { - const callExpression = tryCast(propertyAccessExpression.parent, isCallExpression); - if (callExpression && callExpression.expression === propertyAccessExpression) { - return callExpression; - } - } - break; - // Method call (x['foo'](...)) - case SyntaxKind.ElementAccessExpression: - const elementAccessExpression = tryCast(parent, isElementAccessExpression); - if (elementAccessExpression && elementAccessExpression.parent && elementAccessExpression.argumentExpression === functionRef) { - const callExpression = tryCast(elementAccessExpression.parent, isCallExpression); - if (callExpression && callExpression.expression === elementAccessExpression) { - return callExpression; - } - } - break; + function groupReferences(referenceEntries: ReadonlyArray | undefined): GroupedReferences { + const references: GroupedReferences = { calls: [], declarations: [], unhandled: [] }; + forEach(referenceEntries, (entry) => { + const decl = entryToDeclarationName(entry); + if (decl) { + references.declarations.push(decl); + return; } + const call = entryToFunctionCall(entry); + if (call) { + references.calls.push(call); + return; + } + const node = entryToNode(entry); + if (node) { + references.unhandled.push(node); + } + }); + return references; + + function entryToFunctionCall(entry: FindAllReferences.Entry): CallExpression | NewExpression | undefined { + if (entry.kind !== FindAllReferences.EntryKind.Span && entry.node && entry.node.parent) { + const functionRef = entry.node; + const parent = functionRef.parent; + switch (parent.kind) { + // Function call (foo(...)) + case SyntaxKind.CallExpression: + const callExpression = tryCast(parent, isCallExpression); + if (callExpression && callExpression.expression === functionRef) { + return callExpression; + } + break; + // Constructor call (new Foo(...)) + case SyntaxKind.NewExpression: + const newExpression = tryCast(parent, isNewExpression); + if (newExpression && newExpression.expression === functionRef) { + return newExpression; + } + break; + // Method call (x.foo(...)) + case SyntaxKind.PropertyAccessExpression: + const propertyAccessExpression = tryCast(parent, isPropertyAccessExpression); + if (propertyAccessExpression && propertyAccessExpression.parent && propertyAccessExpression.name === functionRef) { + const callExpression = tryCast(propertyAccessExpression.parent, isCallExpression); + if (callExpression && callExpression.expression === propertyAccessExpression) { + return callExpression; + } + } + break; + // Method call (x['foo'](...)) + case SyntaxKind.ElementAccessExpression: + const elementAccessExpression = tryCast(parent, isElementAccessExpression); + if (elementAccessExpression && elementAccessExpression.parent && elementAccessExpression.argumentExpression === functionRef) { + const callExpression = tryCast(elementAccessExpression.parent, isCallExpression); + if (callExpression && callExpression.expression === elementAccessExpression) { + return callExpression; + } + } + break; + } + } + return undefined; } - return undefined; - } - - function entryToDeclarationName(entry: FindAllReferences.Entry): Node | undefined { - if (entry.kind !== FindAllReferences.EntryKind.Span && entry.node && contains(names, entry.node)) { - return entry.node; + + function entryToDeclarationName(entry: FindAllReferences.Entry): Node | undefined { + if (entry.kind !== FindAllReferences.EntryKind.Span && entry.node && contains(functionNames, entry.node)) { + return entry.node; + } + return undefined; } - return undefined; - } - - function entryToNode(entry: FindAllReferences.Entry): Node | undefined { - if (entry.kind !== FindAllReferences.EntryKind.Span && entry.node) { - return entry.node; + + function entryToNode(entry: FindAllReferences.Entry): Node | undefined { + if (entry.kind !== FindAllReferences.EntryKind.Span && entry.node) { + return entry.node; + } + return undefined; } - return undefined; } } - interface GroupedReferences { - calls: (CallExpression | NewExpression)[]; - declarations: Node[]; - unhandled: Node[]; + function checkReferences(functionNames: Node[], groupedReferences: GroupedReferences): boolean { + if (groupedReferences.unhandled.length > 0) { + return false; + } + if (groupedReferences.declarations.length > functionNames.length) { + return false; + } + return true; } function getFunctionDeclarationAtPosition(file: SourceFile, startPosition: number, checker: TypeChecker): ValidFunctionDeclaration | undefined { @@ -412,4 +411,10 @@ namespace ts.refactor.convertToNamedParameters { modifiers: undefined; decorators: undefined; } + + interface GroupedReferences { + calls: (CallExpression | NewExpression)[]; + declarations: Node[]; + unhandled: Node[]; + } } \ No newline at end of file From 5ec35c1ee80a621cec8066bdd53a000b4b4a633f Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Wed, 13 Feb 2019 17:27:28 -0800 Subject: [PATCH 061/149] Readd configure-insiders task to Gulpfile (#29907) It's identical to configure-nightly but with the flag changed from dev to insiders. We use it to manually publish an insiders build via pipeline, and went missing when we copied functionality from the jakefile. --- Gulpfile.js | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Gulpfile.js b/Gulpfile.js index 68a2b79f222..7d31e0a6137 100644 --- a/Gulpfile.js +++ b/Gulpfile.js @@ -618,6 +618,10 @@ const configureNightly = () => exec(process.execPath, ["scripts/configurePrerele task("configure-nightly", series(buildScripts, configureNightly)); task("configure-nightly").description = "Runs scripts/configurePrerelease.ts to prepare a build for nightly publishing"; +const configureInsiders = () => exec(process.execPath, ["scripts/configurePrerelease.js", "insiders", "package.json", "src/compiler/core.ts"]) +task("configure-insiders", series(buildScripts, configureInsiders)); +task("configure-insiders").description = "Runs scripts/configurePrerelease.ts to prepare a build for insiders publishing"; + const publishNightly = () => exec("npm", ["publish", "--tag", "next"]); task("publish-nightly", series(task("clean"), task("LKG"), task("clean"), task("runtests-parallel"), publishNightly)); task("publish-nightly").description = "Runs `npm publish --tag next` to create a new nightly build on npm"; From c358b0b4a547866b1fd8fba15dcb8ff31b812ea1 Mon Sep 17 00:00:00 2001 From: Titian Cernicova-Dragomir Date: Thu, 14 Feb 2019 07:23:11 +0200 Subject: [PATCH 062/149] Fixed tslint error. --- src/compiler/checker.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index a1248d536a8..0dce8cf8eca 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -1518,7 +1518,7 @@ namespace ts { !checkAndReportErrorForExtendingInterface(errorLocation) && !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) && !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) && - !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) && + !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) && !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) { let suggestion: Symbol | undefined; if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) { From 84076a55351684296f7b3f1d2715690acbe8039f Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Wed, 13 Feb 2019 22:54:33 -0800 Subject: [PATCH 063/149] Add diagnostic context for expando property declarations (#29905) --- src/compiler/transformers/declarations.ts | 2 ++ .../transformers/declarations/diagnostics.ts | 10 +++--- ...nEmitExpandoPropertyPrivateName.errors.txt | 14 +++++++++ ...clarationEmitExpandoPropertyPrivateName.js | 31 +++++++++++++++++++ ...tionEmitExpandoPropertyPrivateName.symbols | 22 +++++++++++++ ...rationEmitExpandoPropertyPrivateName.types | 22 +++++++++++++ ...clarationEmitExpandoPropertyPrivateName.ts | 9 ++++++ .../TypeScript-Node-Starter | 2 +- tests/cases/user/prettier/prettier | 2 +- tests/cases/user/webpack/webpack | 2 +- 10 files changed, 109 insertions(+), 7 deletions(-) create mode 100644 tests/baselines/reference/declarationEmitExpandoPropertyPrivateName.errors.txt create mode 100644 tests/baselines/reference/declarationEmitExpandoPropertyPrivateName.js create mode 100644 tests/baselines/reference/declarationEmitExpandoPropertyPrivateName.symbols create mode 100644 tests/baselines/reference/declarationEmitExpandoPropertyPrivateName.types create mode 100644 tests/cases/compiler/declarationEmitExpandoPropertyPrivateName.ts diff --git a/src/compiler/transformers/declarations.ts b/src/compiler/transformers/declarations.ts index 42bb5d77931..63c340d81dc 100644 --- a/src/compiler/transformers/declarations.ts +++ b/src/compiler/transformers/declarations.ts @@ -1006,7 +1006,9 @@ namespace ts { if (!isPropertyAccessExpression(p.valueDeclaration)) { return undefined; } + getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(p.valueDeclaration); const type = resolver.createTypeOfDeclaration(p.valueDeclaration, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker); + getSymbolAccessibilityDiagnostic = oldDiag; const varDecl = createVariableDeclaration(unescapeLeadingUnderscores(p.escapedName), type, /*initializer*/ undefined); return createVariableStatement(/*modifiers*/ undefined, createVariableDeclarationList([varDecl])); }); diff --git a/src/compiler/transformers/declarations/diagnostics.ts b/src/compiler/transformers/declarations/diagnostics.ts index b4c72c79012..9a9aed99e47 100644 --- a/src/compiler/transformers/declarations/diagnostics.ts +++ b/src/compiler/transformers/declarations/diagnostics.ts @@ -26,7 +26,8 @@ namespace ts { | ImportEqualsDeclaration | TypeAliasDeclaration | ConstructorDeclaration - | IndexSignatureDeclaration; + | IndexSignatureDeclaration + | PropertyAccessExpression; export function canProduceDiagnostics(node: Node): node is DeclarationDiagnosticProducing { return isVariableDeclaration(node) || @@ -46,7 +47,8 @@ namespace ts { isImportEqualsDeclaration(node) || isTypeAliasDeclaration(node) || isConstructorDeclaration(node) || - isIndexSignatureDeclaration(node); + isIndexSignatureDeclaration(node) || + isPropertyAccessExpression(node); } export function createGetSymbolAccessibilityDiagnosticForNodeName(node: DeclarationDiagnosticProducing) { @@ -123,7 +125,7 @@ namespace ts { } export function createGetSymbolAccessibilityDiagnosticForNode(node: DeclarationDiagnosticProducing): (symbolAccessibilityResult: SymbolAccessibilityResult) => SymbolAccessibilityDiagnostic | undefined { - if (isVariableDeclaration(node) || isPropertyDeclaration(node) || isPropertySignature(node) || isBindingElement(node) || isConstructorDeclaration(node)) { + if (isVariableDeclaration(node) || isPropertyDeclaration(node) || isPropertySignature(node) || isPropertyAccessExpression(node) || isBindingElement(node) || isConstructorDeclaration(node)) { return getVariableDeclarationTypeVisibilityError; } else if (isSetAccessor(node) || isGetAccessor(node)) { @@ -164,7 +166,7 @@ namespace ts { } // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all. - else if (node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature || + else if (node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertyAccessExpression || node.kind === SyntaxKind.PropertySignature || (node.kind === SyntaxKind.Parameter && hasModifier(node.parent, ModifierFlags.Private))) { // TODO(jfreeman): Deal with computed properties in error reporting. if (hasModifier(node, ModifierFlags.Static)) { diff --git a/tests/baselines/reference/declarationEmitExpandoPropertyPrivateName.errors.txt b/tests/baselines/reference/declarationEmitExpandoPropertyPrivateName.errors.txt new file mode 100644 index 00000000000..343a3a5351a --- /dev/null +++ b/tests/baselines/reference/declarationEmitExpandoPropertyPrivateName.errors.txt @@ -0,0 +1,14 @@ +tests/cases/compiler/b.ts(4,1): error TS4032: Property 'val' of exported interface has or is using name 'I' from private module '"tests/cases/compiler/a"'. + + +==== tests/cases/compiler/a.ts (0 errors) ==== + interface I {} + export function f(): I { return null as I; } +==== tests/cases/compiler/b.ts (1 errors) ==== + import {f} from "./a"; + + export function q() {} + q.val = f(); + ~~~~~ +!!! error TS4032: Property 'val' of exported interface has or is using name 'I' from private module '"tests/cases/compiler/a"'. + \ No newline at end of file diff --git a/tests/baselines/reference/declarationEmitExpandoPropertyPrivateName.js b/tests/baselines/reference/declarationEmitExpandoPropertyPrivateName.js new file mode 100644 index 00000000000..a40fb252760 --- /dev/null +++ b/tests/baselines/reference/declarationEmitExpandoPropertyPrivateName.js @@ -0,0 +1,31 @@ +//// [tests/cases/compiler/declarationEmitExpandoPropertyPrivateName.ts] //// + +//// [a.ts] +interface I {} +export function f(): I { return null as I; } +//// [b.ts] +import {f} from "./a"; + +export function q() {} +q.val = f(); + + +//// [a.js] +"use strict"; +exports.__esModule = true; +function f() { return null; } +exports.f = f; +//// [b.js] +"use strict"; +exports.__esModule = true; +var a_1 = require("./a"); +function q() { } +exports.q = q; +q.val = a_1.f(); + + +//// [a.d.ts] +interface I { +} +export declare function f(): I; +export {}; diff --git a/tests/baselines/reference/declarationEmitExpandoPropertyPrivateName.symbols b/tests/baselines/reference/declarationEmitExpandoPropertyPrivateName.symbols new file mode 100644 index 00000000000..841620f0361 --- /dev/null +++ b/tests/baselines/reference/declarationEmitExpandoPropertyPrivateName.symbols @@ -0,0 +1,22 @@ +=== tests/cases/compiler/a.ts === +interface I {} +>I : Symbol(I, Decl(a.ts, 0, 0)) + +export function f(): I { return null as I; } +>f : Symbol(f, Decl(a.ts, 0, 14)) +>I : Symbol(I, Decl(a.ts, 0, 0)) +>I : Symbol(I, Decl(a.ts, 0, 0)) + +=== tests/cases/compiler/b.ts === +import {f} from "./a"; +>f : Symbol(f, Decl(b.ts, 0, 8)) + +export function q() {} +>q : Symbol(q, Decl(b.ts, 0, 22), Decl(b.ts, 2, 22)) + +q.val = f(); +>q.val : Symbol(q.val, Decl(b.ts, 2, 22)) +>q : Symbol(q, Decl(b.ts, 0, 22), Decl(b.ts, 2, 22)) +>val : Symbol(q.val, Decl(b.ts, 2, 22)) +>f : Symbol(f, Decl(b.ts, 0, 8)) + diff --git a/tests/baselines/reference/declarationEmitExpandoPropertyPrivateName.types b/tests/baselines/reference/declarationEmitExpandoPropertyPrivateName.types new file mode 100644 index 00000000000..7418b414029 --- /dev/null +++ b/tests/baselines/reference/declarationEmitExpandoPropertyPrivateName.types @@ -0,0 +1,22 @@ +=== tests/cases/compiler/a.ts === +interface I {} +export function f(): I { return null as I; } +>f : () => I +>null as I : I +>null : null + +=== tests/cases/compiler/b.ts === +import {f} from "./a"; +>f : () => I + +export function q() {} +>q : typeof q + +q.val = f(); +>q.val = f() : I +>q.val : I +>q : typeof q +>val : I +>f() : I +>f : () => I + diff --git a/tests/cases/compiler/declarationEmitExpandoPropertyPrivateName.ts b/tests/cases/compiler/declarationEmitExpandoPropertyPrivateName.ts new file mode 100644 index 00000000000..09be2a08ff8 --- /dev/null +++ b/tests/cases/compiler/declarationEmitExpandoPropertyPrivateName.ts @@ -0,0 +1,9 @@ +// @declaration: true +// @filename: a.ts +interface I {} +export function f(): I { return null as I; } +// @filename: b.ts +import {f} from "./a"; + +export function q() {} +q.val = f(); diff --git a/tests/cases/user/TypeScript-Node-Starter/TypeScript-Node-Starter b/tests/cases/user/TypeScript-Node-Starter/TypeScript-Node-Starter index 6b9706810b5..40bdb4eadab 160000 --- a/tests/cases/user/TypeScript-Node-Starter/TypeScript-Node-Starter +++ b/tests/cases/user/TypeScript-Node-Starter/TypeScript-Node-Starter @@ -1 +1 @@ -Subproject commit 6b9706810b55af326a93b9aa59cb17815a30bb32 +Subproject commit 40bdb4eadabc9fbed7d83e3f26817a931c0763b6 diff --git a/tests/cases/user/prettier/prettier b/tests/cases/user/prettier/prettier index 6e0de081223..67f1c4877ee 160000 --- a/tests/cases/user/prettier/prettier +++ b/tests/cases/user/prettier/prettier @@ -1 +1 @@ -Subproject commit 6e0de0812231c3a48387d398d092418749aa39f1 +Subproject commit 67f1c4877ee1090b66d468a847caccca411a6f82 diff --git a/tests/cases/user/webpack/webpack b/tests/cases/user/webpack/webpack index a28f44f6132..10282ea2064 160000 --- a/tests/cases/user/webpack/webpack +++ b/tests/cases/user/webpack/webpack @@ -1 +1 @@ -Subproject commit a28f44f613276446fb764dec7fab38b7cff8a07c +Subproject commit 10282ea20648b465caec6448849f24fc34e1ba3e From b57956673e95884023e4bfe6ab308837b3e300c9 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 14 Feb 2019 14:42:55 -0800 Subject: [PATCH 064/149] Move TypeFlags.PropapatingFlags to ObjectFlags to free up 3 flags --- src/compiler/checker.ts | 143 +++++++++++++++++++------------------- src/compiler/types.ts | 105 ++++++++++++++++------------ src/compiler/utilities.ts | 2 +- 3 files changed, 133 insertions(+), 117 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 9021a50ef8d..f76505ad4a5 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -390,10 +390,10 @@ namespace ts { const wildcardType = createIntrinsicType(TypeFlags.Any, "any"); const errorType = createIntrinsicType(TypeFlags.Any, "error"); const unknownType = createIntrinsicType(TypeFlags.Unknown, "unknown"); - const undefinedType = createIntrinsicType(TypeFlags.Undefined, "undefined"); - const undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(TypeFlags.Undefined | TypeFlags.ContainsWideningType, "undefined"); - const nullType = createIntrinsicType(TypeFlags.Null, "null"); - const nullWideningType = strictNullChecks ? nullType : createIntrinsicType(TypeFlags.Null | TypeFlags.ContainsWideningType, "null"); + const undefinedType = createNullableType(TypeFlags.Undefined, "undefined", 0); + const undefinedWideningType = strictNullChecks ? undefinedType : createNullableType(TypeFlags.Undefined, "undefined", ObjectFlags.ContainsWideningType); + const nullType = createNullableType(TypeFlags.Null, "null", 0); + const nullWideningType = strictNullChecks ? nullType : createNullableType(TypeFlags.Null, "null", ObjectFlags.ContainsWideningType); const stringType = createIntrinsicType(TypeFlags.String, "string"); const numberType = createIntrinsicType(TypeFlags.Number, "number"); const bigintType = createIntrinsicType(TypeFlags.BigInt, "bigint"); @@ -439,7 +439,7 @@ namespace ts { const anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes. - anyFunctionType.flags |= TypeFlags.ContainsAnyFunctionType; + anyFunctionType.objectFlags |= ObjectFlags.ContainsAnyFunctionType; const noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); const circularConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); @@ -2741,6 +2741,12 @@ namespace ts { return type; } + function createNullableType(kind: TypeFlags, intrinsicName: string, objectFlags: ObjectFlags): NullableType { + const type = createIntrinsicType(kind, intrinsicName); + type.objectFlags = objectFlags; + return type; + } + function createBooleanType(trueFalseTypes: ReadonlyArray): IntrinsicType & UnionType { const type = getUnionType(trueFalseTypes); type.flags |= TypeFlags.Boolean; @@ -5128,7 +5134,7 @@ namespace ts { definedInConstructor = true; } } - const sourceTypes = some(constructorTypes, t => !!(t.flags & ~(TypeFlags.Nullable | TypeFlags.ContainsWideningType))) ? constructorTypes : types; // TODO: GH#18217 + const sourceTypes = some(constructorTypes, t => !!(t.flags & ~TypeFlags.Nullable)) ? constructorTypes : types; // TODO: GH#18217 type = getUnionType(sourceTypes!, UnionReduction.Subtype); } const widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor)); @@ -5293,7 +5299,7 @@ namespace ts { function getTypeFromObjectBindingPattern(pattern: ObjectBindingPattern, includePatternInType: boolean, reportErrors: boolean): Type { const members = createSymbolTable(); let stringIndexInfo: IndexInfo | undefined; - let objectFlags = ObjectFlags.ObjectLiteral; + let objectFlags = ObjectFlags.ObjectLiteral | ObjectFlags.ContainsObjectLiteral; forEach(pattern.elements, e => { const name = e.propertyName || e.name; if (e.dotDotDotToken) { @@ -5315,7 +5321,6 @@ namespace ts { members.set(symbol.escapedName, symbol); }); const result = createAnonymousType(undefined, members, emptyArray, emptyArray, stringIndexInfo, undefined); - result.flags |= TypeFlags.ContainsObjectLiteral; result.objectFlags |= objectFlags; if (includePatternInType) { result.pattern = pattern; @@ -8540,14 +8545,14 @@ namespace ts { // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type // of an object literal or the anyFunctionType. This is because there are operations in the type checker // that care about the presence of such types at arbitrary depth in a containing type. - function getPropagatingFlagsOfTypes(types: ReadonlyArray, excludeKinds: TypeFlags): TypeFlags { - let result: TypeFlags = 0; + function getPropagatingFlagsOfTypes(types: ReadonlyArray, excludeKinds: TypeFlags): ObjectFlags { + let result: ObjectFlags = 0; for (const type of types) { if (!(type.flags & excludeKinds)) { - result |= type.flags; + result |= getObjectFlags(type); } } - return result & TypeFlags.PropagatingFlags; + return result & ObjectFlags.PropagatingFlags; } function createTypeReference(target: GenericType, typeArguments: ReadonlyArray | undefined): TypeReference { @@ -8556,7 +8561,7 @@ namespace ts { if (!type) { type = createObjectType(ObjectFlags.Reference, target.symbol); target.instantiations.set(id, type); - type.flags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0; + type.objectFlags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0; type.target = target; type.typeArguments = typeArguments; } @@ -9235,10 +9240,11 @@ namespace ts { // intersections of unit types into 'never' upon construction, but deferring the reduction makes it // easier to reason about their origin. if (!(flags & TypeFlags.Never || flags & TypeFlags.Intersection && isEmptyIntersectionType(type))) { - includes |= flags & ~TypeFlags.ConstructionFlags; - if (type === wildcardType) includes |= TypeFlags.Wildcard; + includes |= flags & TypeFlags.IncludesMask; + if (flags & TypeFlags.StructuredOrInstantiable) includes |= TypeFlags.IncludesStructuredOrInstantiable; + if (type === wildcardType) includes |= TypeFlags.IncludesWildcard; if (!strictNullChecks && flags & TypeFlags.Nullable) { - if (!(flags & TypeFlags.ContainsWideningType)) includes |= TypeFlags.NonWideningType; + if (!(getObjectFlags(type) & ObjectFlags.ContainsWideningType)) includes |= TypeFlags.IncludesNonWideningType; } else { const len = typeSet.length; @@ -9349,7 +9355,7 @@ namespace ts { const includes = addTypesToUnion(typeSet, 0, types); if (unionReduction !== UnionReduction.None) { if (includes & TypeFlags.AnyOrUnknown) { - return includes & TypeFlags.Any ? includes & TypeFlags.Wildcard ? wildcardType : anyType : unknownType; + return includes & TypeFlags.Any ? includes & TypeFlags.IncludesWildcard ? wildcardType : anyType : unknownType; } switch (unionReduction) { case UnionReduction.Literal: @@ -9358,18 +9364,18 @@ namespace ts { } break; case UnionReduction.Subtype: - if (!removeSubtypes(typeSet, !(includes & TypeFlags.StructuredOrInstantiable))) { + if (!removeSubtypes(typeSet, !(includes & TypeFlags.IncludesStructuredOrInstantiable))) { return errorType; } break; } if (typeSet.length === 0) { - return includes & TypeFlags.Null ? includes & TypeFlags.NonWideningType ? nullType : nullWideningType : - includes & TypeFlags.Undefined ? includes & TypeFlags.NonWideningType ? undefinedType : undefinedWideningType : + return includes & TypeFlags.Null ? includes & TypeFlags.IncludesNonWideningType ? nullType : nullWideningType : + includes & TypeFlags.Undefined ? includes & TypeFlags.IncludesNonWideningType ? undefinedType : undefinedWideningType : neverType; } } - return getUnionTypeFromSortedList(typeSet, !(includes & TypeFlags.NotPrimitiveUnion), aliasSymbol, aliasTypeArguments); + return getUnionTypeFromSortedList(typeSet, includes & TypeFlags.NotPrimitiveUnion ? 0 : ObjectFlags.PrimitiveUnion, aliasSymbol, aliasTypeArguments); } function getUnionTypePredicate(signatures: ReadonlyArray): TypePredicate | undefined { @@ -9409,7 +9415,7 @@ namespace ts { } // This function assumes the constituent type list is sorted and deduplicated. - function getUnionTypeFromSortedList(types: Type[], primitiveTypesOnly: boolean, aliasSymbol?: Symbol, aliasTypeArguments?: ReadonlyArray): Type { + function getUnionTypeFromSortedList(types: Type[], objectFlags: ObjectFlags, aliasSymbol?: Symbol, aliasTypeArguments?: ReadonlyArray): Type { if (types.length === 0) { return neverType; } @@ -9419,11 +9425,10 @@ namespace ts { const id = getTypeListId(types); let type = unionTypes.get(id); if (!type) { - const propagatedFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ TypeFlags.Nullable); - type = createType(TypeFlags.Union | propagatedFlags); + type = createType(TypeFlags.Union); unionTypes.set(id, type); + type.objectFlags = objectFlags | getPropagatingFlagsOfTypes(types, /*excludeKinds*/ TypeFlags.Nullable); type.types = types; - type.primitiveTypesOnly = primitiveTypesOnly; /* Note: This is the alias symbol (or lack thereof) that we see when we first encounter this union type. For aliases of identical unions, eg `type T = A | B; type U = A | B`, the symbol of the first alias encountered is the aliasSymbol. @@ -9452,15 +9457,15 @@ namespace ts { return addTypesToIntersection(typeSet, includes, (type).types); } if (isEmptyAnonymousObjectType(type)) { - if (!(includes & TypeFlags.EmptyObject)) { - includes |= TypeFlags.EmptyObject; + if (!(includes & TypeFlags.IncludesEmptyObject)) { + includes |= TypeFlags.IncludesEmptyObject; typeSet.push(type); } } else { - includes |= flags & ~TypeFlags.ConstructionFlags; + includes |= flags & TypeFlags.IncludesMask; if (flags & TypeFlags.AnyOrUnknown) { - if (type === wildcardType) includes |= TypeFlags.Wildcard; + if (type === wildcardType) includes |= TypeFlags.IncludesWildcard; } else if ((strictNullChecks || !(flags & TypeFlags.Nullable)) && !contains(typeSet, type)) { typeSet.push(type); @@ -9518,7 +9523,7 @@ namespace ts { // other unions and return true. Otherwise, do nothing and return false. function intersectUnionsOfPrimitiveTypes(types: Type[]) { let unionTypes: UnionType[] | undefined; - const index = findIndex(types, t => !!(t.flags & TypeFlags.Union) && (t).primitiveTypesOnly); + const index = findIndex(types, t => !!(getObjectFlags(t) & ObjectFlags.PrimitiveUnion)); if (index < 0) { return false; } @@ -9527,7 +9532,7 @@ namespace ts { // the unionTypes array. while (i < types.length) { const t = types[i]; - if (t.flags & TypeFlags.Union && (t).primitiveTypesOnly) { + if (getObjectFlags(t) & ObjectFlags.PrimitiveUnion) { (unionTypes || (unionTypes = [types[index]])).push(t); orderedRemoveItemAt(types, i); } @@ -9554,7 +9559,7 @@ namespace ts { } } // Finally replace the first union with the result - types[index] = getUnionTypeFromSortedList(result, /*primitiveTypesOnly*/ true); + types[index] = getUnionTypeFromSortedList(result, ObjectFlags.PrimitiveUnion); return true; } @@ -9575,7 +9580,7 @@ namespace ts { return neverType; } if (includes & TypeFlags.Any) { - return includes & TypeFlags.Wildcard ? wildcardType : anyType; + return includes & TypeFlags.IncludesWildcard ? wildcardType : anyType; } if (!strictNullChecks && includes & TypeFlags.Nullable) { return includes & TypeFlags.Undefined ? undefinedType : nullType; @@ -9586,7 +9591,7 @@ namespace ts { includes & TypeFlags.ESSymbol && includes & TypeFlags.UniqueESSymbol) { removeRedundantPrimitiveTypes(typeSet, includes); } - if (includes & TypeFlags.EmptyObject && includes & TypeFlags.Object) { + if (includes & TypeFlags.IncludesEmptyObject && includes & TypeFlags.Object) { orderedRemoveItemAt(typeSet, findIndex(typeSet, isEmptyAnonymousObjectType)); } if (typeSet.length === 0) { @@ -9612,9 +9617,9 @@ namespace ts { const id = getTypeListId(typeSet); let type = intersectionTypes.get(id); if (!type) { - const propagatedFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ TypeFlags.Nullable); - type = createType(TypeFlags.Intersection | propagatedFlags); + type = createType(TypeFlags.Intersection); intersectionTypes.set(id, type); + type.objectFlags = getPropagatingFlagsOfTypes(typeSet, /*excludeKinds*/ TypeFlags.Nullable); type.types = typeSet; type.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`. type.aliasTypeArguments = aliasTypeArguments; @@ -10273,7 +10278,7 @@ namespace ts { * this function should be called in a left folding style, with left = previous result of getSpreadType * and right = the new element to be spread. */ - function getSpreadType(left: Type, right: Type, symbol: Symbol | undefined, typeFlags: TypeFlags, objectFlags: ObjectFlags, readonly: boolean): Type { + function getSpreadType(left: Type, right: Type, symbol: Symbol | undefined, objectFlags: ObjectFlags, readonly: boolean): Type { if (left.flags & TypeFlags.Any || right.flags & TypeFlags.Any) { return anyType; } @@ -10287,10 +10292,10 @@ namespace ts { return left; } if (left.flags & TypeFlags.Union) { - return mapType(left, t => getSpreadType(t, right, symbol, typeFlags, objectFlags, readonly)); + return mapType(left, t => getSpreadType(t, right, symbol, objectFlags, readonly)); } if (right.flags & TypeFlags.Union) { - return mapType(right, t => getSpreadType(left, t, symbol, typeFlags, objectFlags, readonly)); + return mapType(right, t => getSpreadType(left, t, symbol, objectFlags, readonly)); } if (right.flags & (TypeFlags.BooleanLike | TypeFlags.NumberLike | TypeFlags.BigIntLike | TypeFlags.StringLike | TypeFlags.EnumLike | TypeFlags.NonPrimitive | TypeFlags.Index)) { return left; @@ -10307,7 +10312,7 @@ namespace ts { const types = (left).types; const lastLeft = types[types.length - 1]; if (isNonGenericObjectType(lastLeft) && isNonGenericObjectType(right)) { - return getIntersectionType(concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, typeFlags, objectFlags, readonly)])); + return getIntersectionType(concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, objectFlags, readonly)])); } } return getIntersectionType([left, right]); @@ -10367,8 +10372,7 @@ namespace ts { emptyArray, getIndexInfoWithReadonly(stringIndexInfo, readonly), getIndexInfoWithReadonly(numberIndexInfo, readonly)); - spread.flags |= TypeFlags.ContainsObjectLiteral | typeFlags; - spread.objectFlags |= ObjectFlags.ObjectLiteral | ObjectFlags.ContainsSpread | objectFlags; + spread.objectFlags |= ObjectFlags.ObjectLiteral | ObjectFlags.ContainsObjectLiteral | ObjectFlags.ContainsSpread | objectFlags; return spread; } @@ -13853,7 +13857,7 @@ namespace ts { resolved.stringIndexInfo, resolved.numberIndexInfo); regularNew.flags = resolved.flags; - regularNew.objectFlags |= ObjectFlags.ObjectLiteral | (getObjectFlags(resolved) & ObjectFlags.JSLiteral); + regularNew.objectFlags |= resolved.objectFlags & ~ObjectFlags.FreshLiteral; (type).regularType = regularNew; return regularNew; } @@ -13944,7 +13948,7 @@ namespace ts { } function getWidenedTypeWithContext(type: Type, context: WideningContext | undefined): Type { - if (type.flags & TypeFlags.RequiresWidening) { + if (getObjectFlags(type) & ObjectFlags.RequiresWidening) { if (type.flags & TypeFlags.Nullable) { return anyType; } @@ -13982,7 +13986,7 @@ namespace ts { */ function reportWideningErrorsInType(type: Type): boolean { let errorReported = false; - if (type.flags & TypeFlags.ContainsWideningType) { + if (getObjectFlags(type) & ObjectFlags.ContainsWideningType) { if (type.flags & TypeFlags.Union) { if (some((type).types, isEmptyObjectType)) { errorReported = true; @@ -14005,7 +14009,7 @@ namespace ts { if (isObjectLiteralType(type)) { for (const p of getPropertiesOfObjectType(type)) { const t = getTypeOfSymbol(p); - if (t.flags & TypeFlags.ContainsWideningType) { + if (getObjectFlags(t) & ObjectFlags.ContainsWideningType) { if (!reportWideningErrorsInType(t)) { error(p.valueDeclaration, Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t))); } @@ -14080,7 +14084,7 @@ namespace ts { } function reportErrorsFromWidening(declaration: Declaration, type: Type) { - if (produceDiagnostics && noImplicitAny && type.flags & TypeFlags.ContainsWideningType) { + if (produceDiagnostics && noImplicitAny && getObjectFlags(type) & ObjectFlags.ContainsWideningType) { // Report implicit any error within type if possible, otherwise report error on declaration if (!reportWideningErrorsInType(type)) { reportImplicitAny(declaration, type); @@ -14225,7 +14229,7 @@ namespace ts { // If any property contains context sensitive functions that have been skipped, the source type // is incomplete and we can't infer a meaningful input type. for (const prop of properties) { - if (getTypeOfSymbol(prop).flags & TypeFlags.ContainsAnyFunctionType) { + if (getObjectFlags(getTypeOfSymbol(prop)) & ObjectFlags.ContainsAnyFunctionType) { return undefined; } } @@ -14383,7 +14387,7 @@ namespace ts { // not contain anyFunctionType when we come back to this argument for its second round // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard // when constructing types from type parameters that had no inference candidates). - if (source.flags & TypeFlags.ContainsAnyFunctionType || source === silentNeverType || (priority & InferencePriority.ReturnType && (source === autoType || source === autoArrayType))) { + if (getObjectFlags(source) & ObjectFlags.ContainsAnyFunctionType || source === silentNeverType || (priority & InferencePriority.ReturnType && (source === autoType || source === autoArrayType))) { return; } const inference = getInferenceInfoForType(target); @@ -14686,7 +14690,7 @@ namespace ts { const sourceLen = sourceSignatures.length; const targetLen = targetSignatures.length; const len = sourceLen < targetLen ? sourceLen : targetLen; - const skipParameters = !!(source.flags & TypeFlags.ContainsAnyFunctionType); + const skipParameters = !!(getObjectFlags(source) & ObjectFlags.ContainsAnyFunctionType); for (let i = 0; i < len; i++) { inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getBaseSignature(targetSignatures[targetLen - len + i]), skipParameters); } @@ -15444,7 +15448,7 @@ namespace ts { if (type.flags & TypeFlags.Union) { const types = (type).types; const filtered = filter(types, f); - return filtered === types ? type : getUnionTypeFromSortedList(filtered, (type).primitiveTypesOnly); + return filtered === types ? type : getUnionTypeFromSortedList(filtered, (type).objectFlags); } return f(type) ? type : neverType; } @@ -18350,7 +18354,7 @@ namespace ts { let propertiesTable: SymbolTable; let propertiesArray: Symbol[] = []; let spread: Type = emptyObjectType; - let propagatedFlags: TypeFlags = 0; + let propagatedFlags: ObjectFlags = 0; const contextualType = getApparentTypeOfContextualType(node); const contextualTypeHasPattern = contextualType && contextualType.pattern && @@ -18360,7 +18364,7 @@ namespace ts { const isInJavascript = isInJSFile(node) && !isInJsonFile(node); const enumTag = getJSDocEnumTag(node); const isJSObjectLiteral = !contextualType && isInJavascript && !enumTag; - let typeFlags: TypeFlags = 0; + let objectFlags: ObjectFlags = 0; let patternWithComputedProperties = false; let hasComputedStringProperty = false; let hasComputedNumberProperty = false; @@ -18388,7 +18392,7 @@ namespace ts { checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl); } } - typeFlags |= type.flags; + objectFlags |= getObjectFlags(type); const nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined; const prop = nameType ? createSymbol(SymbolFlags.Property | member.flags, getPropertyNameFromType(nameType), checkFlags | CheckFlags.Late) : @@ -18436,19 +18440,19 @@ namespace ts { checkExternalEmitHelpers(memberDecl, ExternalEmitHelpers.Assign); } if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, ObjectFlags.FreshLiteral, inConstContext); + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags | ObjectFlags.FreshLiteral, inConstContext); propertiesArray = []; propertiesTable = createSymbolTable(); hasComputedStringProperty = false; hasComputedNumberProperty = false; - typeFlags = 0; + objectFlags = 0; } const type = checkExpression(memberDecl.expression); if (!isValidSpreadType(type)) { error(memberDecl, Diagnostics.Spread_types_may_only_be_created_from_object_types); return errorType; } - spread = getSpreadType(spread, type, node.symbol, propagatedFlags, ObjectFlags.FreshLiteral, inConstContext); + spread = getSpreadType(spread, type, node.symbol, propagatedFlags | ObjectFlags.FreshLiteral, inConstContext); offset = i + 1; continue; } @@ -18498,7 +18502,7 @@ namespace ts { if (spread !== emptyObjectType) { if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags, ObjectFlags.FreshLiteral, inConstContext); + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags | ObjectFlags.FreshLiteral, inConstContext); } return spread; } @@ -18509,8 +18513,7 @@ namespace ts { const stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, IndexKind.String) : undefined; const numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, IndexKind.Number) : undefined; const result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); - result.flags |= TypeFlags.ContainsObjectLiteral | typeFlags & TypeFlags.PropagatingFlags; - result.objectFlags |= ObjectFlags.ObjectLiteral | freshObjectLiteralFlag; + result.objectFlags |= ObjectFlags.ObjectLiteral | ObjectFlags.ContainsObjectLiteral | freshObjectLiteralFlag | objectFlags & ObjectFlags.PropagatingFlags; if (isJSObjectLiteral) { result.objectFlags |= ObjectFlags.JSLiteral; } @@ -18520,7 +18523,7 @@ namespace ts { if (inDestructuringPattern) { result.pattern = node; } - propagatedFlags |= result.flags & TypeFlags.PropagatingFlags; + propagatedFlags |= result.objectFlags & ObjectFlags.PropagatingFlags; return result; } } @@ -18611,7 +18614,6 @@ namespace ts { let hasSpreadAnyType = false; let typeToIntersect: Type | undefined; let explicitlySpecifyChildrenAttribute = false; - let typeFlags: TypeFlags = 0; let objectFlags: ObjectFlags = ObjectFlags.JsxAttributes; const jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement)); @@ -18619,7 +18621,7 @@ namespace ts { const member = attributeDecl.symbol; if (isJsxAttribute(attributeDecl)) { const exprType = checkJsxAttribute(attributeDecl, checkMode); - typeFlags |= exprType.flags & TypeFlags.PropagatingFlags; + objectFlags |= getObjectFlags(exprType) & ObjectFlags.PropagatingFlags; const attributeSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient | member.flags, member.escapedName); attributeSymbol.declarations = member.declarations; @@ -18637,7 +18639,7 @@ namespace ts { else { Debug.assert(attributeDecl.kind === SyntaxKind.JsxSpreadAttribute); if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags, /*readonly*/ false); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false); attributesTable = createSymbolTable(); } const exprType = checkExpressionCached(attributeDecl.expression, checkMode); @@ -18645,7 +18647,7 @@ namespace ts { hasSpreadAnyType = true; } if (isValidSpreadType(exprType)) { - spread = getSpreadType(spread, exprType, attributes.symbol, typeFlags, objectFlags, /*readonly*/ false); + spread = getSpreadType(spread, exprType, attributes.symbol, objectFlags, /*readonly*/ false); } else { typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType; @@ -18655,7 +18657,7 @@ namespace ts { if (!hasSpreadAnyType) { if (attributesTable.size > 0) { - spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, typeFlags, objectFlags, /*readonly*/ false); + spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false); } } @@ -18687,7 +18689,7 @@ namespace ts { const childPropMap = createSymbolTable(); childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol); spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, emptyArray, emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), - attributes.symbol, typeFlags, objectFlags, /*readonly*/ false); + attributes.symbol, objectFlags, /*readonly*/ false); } } @@ -18708,8 +18710,7 @@ namespace ts { function createJsxAttributesType() { objectFlags |= freshObjectLiteralFlag; const result = createAnonymousType(attributes.symbol, attributesTable, emptyArray, emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.flags |= TypeFlags.ContainsObjectLiteral | typeFlags; - result.objectFlags |= ObjectFlags.ObjectLiteral | objectFlags; + result.objectFlags |= ObjectFlags.ObjectLiteral | ObjectFlags.ContainsObjectLiteral | objectFlags; return result; } } @@ -21374,7 +21375,7 @@ namespace ts { const anonymousSymbol = createSymbol(SymbolFlags.TypeLiteral, InternalSymbolName.Type); const defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, emptyArray, emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); anonymousSymbol.type = defaultContainingObject; - synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*typeFLags*/ 0, /*objectFlags*/ 0, /*readonly*/ false) : defaultContainingObject; + synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*objectFlags*/ 0, /*readonly*/ false) : defaultContainingObject; } else { synthType.syntheticType = type; @@ -22052,7 +22053,7 @@ namespace ts { const returnType = getReturnTypeFromBody(node, checkMode); const returnOnlySignature = createSignature(undefined, undefined, undefined, emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); const returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], emptyArray, undefined, undefined); - returnOnlyType.flags |= TypeFlags.ContainsAnyFunctionType; + returnOnlyType.objectFlags |= ObjectFlags.ContainsAnyFunctionType; return links.contextFreeType = returnOnlyType; } return anyFunctionType; diff --git a/src/compiler/types.ts b/src/compiler/types.ts index a524ce13cb9..c0ae3b99c44 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -3817,39 +3817,33 @@ namespace ts { } export const enum TypeFlags { - Any = 1 << 0, - Unknown = 1 << 1, - String = 1 << 2, - Number = 1 << 3, - Boolean = 1 << 4, - Enum = 1 << 5, - BigInt = 1 << 6, - StringLiteral = 1 << 7, - NumberLiteral = 1 << 8, - BooleanLiteral = 1 << 9, - EnumLiteral = 1 << 10, // Always combined with StringLiteral, NumberLiteral, or Union - BigIntLiteral = 1 << 11, - ESSymbol = 1 << 12, // Type of symbol primitive introduced in ES6 - UniqueESSymbol = 1 << 13, // unique symbol - Void = 1 << 14, - Undefined = 1 << 15, - Null = 1 << 16, - Never = 1 << 17, // Never type - TypeParameter = 1 << 18, // Type parameter - Object = 1 << 19, // Object type - Union = 1 << 20, // Union (T | U) - Intersection = 1 << 21, // Intersection (T & U) - Index = 1 << 22, // keyof T - IndexedAccess = 1 << 23, // T[K] - Conditional = 1 << 24, // T extends U ? X : Y - Substitution = 1 << 25, // Type parameter substitution - NonPrimitive = 1 << 26, // intrinsic object type - /* @internal */ - ContainsWideningType = 1 << 27, // Type is or contains undefined or null widening type - /* @internal */ - ContainsObjectLiteral = 1 << 28, // Type is or contains object literal type - /* @internal */ - ContainsAnyFunctionType = 1 << 29, // Type is or contains the anyFunctionType + Any = 1 << 0, + Unknown = 1 << 1, + String = 1 << 2, + Number = 1 << 3, + Boolean = 1 << 4, + Enum = 1 << 5, + BigInt = 1 << 6, + StringLiteral = 1 << 7, + NumberLiteral = 1 << 8, + BooleanLiteral = 1 << 9, + EnumLiteral = 1 << 10, // Always combined with StringLiteral, NumberLiteral, or Union + BigIntLiteral = 1 << 11, + ESSymbol = 1 << 12, // Type of symbol primitive introduced in ES6 + UniqueESSymbol = 1 << 13, // unique symbol + Void = 1 << 14, + Undefined = 1 << 15, + Null = 1 << 16, + Never = 1 << 17, // Never type + TypeParameter = 1 << 18, // Type parameter + Object = 1 << 19, // Object type + Union = 1 << 20, // Union (T | U) + Intersection = 1 << 21, // Intersection (T & U) + Index = 1 << 22, // keyof T + IndexedAccess = 1 << 23, // T[K] + Conditional = 1 << 24, // T extends U ? X : Y + Substitution = 1 << 25, // Type parameter substitution + NonPrimitive = 1 << 26, // intrinsic object type /* @internal */ AnyOrUnknown = Any | Unknown, @@ -3883,29 +3877,29 @@ namespace ts { InstantiablePrimitive = Index, Instantiable = InstantiableNonPrimitive | InstantiablePrimitive, StructuredOrInstantiable = StructuredType | Instantiable, - + /* @internal */ + ObjectFlagsType = Nullable | Object | Union | Intersection, // 'Narrowable' types are types where narrowing actually narrows. // This *should* be every type other than null, undefined, void, and never Narrowable = Any | Unknown | StructuredOrInstantiable | StringLike | NumberLike | BigIntLike | BooleanLike | ESSymbol | UniqueESSymbol | NonPrimitive, NotUnionOrUnit = Any | Unknown | ESSymbol | Object | NonPrimitive, /* @internal */ NotPrimitiveUnion = Any | Unknown | Enum | Void | Never | StructuredOrInstantiable, + // The following flags are aggregated during union and intersection type construction /* @internal */ - RequiresWidening = ContainsWideningType | ContainsObjectLiteral, - /* @internal */ - PropagatingFlags = ContainsWideningType | ContainsObjectLiteral | ContainsAnyFunctionType, + IncludesMask = Any | Unknown | Primitive | Never | Object | Union, // The following flags are used for different purposes during union and intersection type construction /* @internal */ - NonWideningType = ContainsWideningType, + IncludesStructuredOrInstantiable = TypeParameter, /* @internal */ - Wildcard = ContainsObjectLiteral, + IncludesNonWideningType = Intersection, /* @internal */ - EmptyObject = ContainsAnyFunctionType, + IncludesWildcard = Index, /* @internal */ - ConstructionFlags = NonWideningType | Wildcard | EmptyObject, + IncludesEmptyObject = IndexedAccess, // The following flag is used for different purposes by maybeTypeOfKind /* @internal */ - GenericMappedType = ContainsWideningType + GenericMappedType = Never, } export type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; @@ -3932,6 +3926,12 @@ namespace ts { // Intrinsic types (TypeFlags.Intrinsic) export interface IntrinsicType extends Type { intrinsicName: string; // Name of intrinsic type + objectFlags: ObjectFlags; + } + + /* @internal */ + export interface NullableType extends IntrinsicType { + objectFlags: ObjectFlags; } /* @internal */ @@ -3991,9 +3991,24 @@ namespace ts { MarkerType = 1 << 13, // Marker type used for variance probing JSLiteral = 1 << 14, // Object type declared in JS - disables errors on read/write of nonexisting members FreshLiteral = 1 << 15, // Fresh object literal - ClassOrInterface = Class | Interface + /* @internal */ + PrimitiveUnion = 1 << 16, // Union of only primitive types + /* @internal */ + ContainsWideningType = 1 << 17, // Type is or contains undefined or null widening type + /* @internal */ + ContainsObjectLiteral = 1 << 18, // Type is or contains object literal type + /* @internal */ + ContainsAnyFunctionType = 1 << 19, // Type is or contains the anyFunctionType + ClassOrInterface = Class | Interface, + /* @internal */ + RequiresWidening = ContainsWideningType | ContainsObjectLiteral, + /* @internal */ + PropagatingFlags = ContainsWideningType | ContainsObjectLiteral | ContainsAnyFunctionType } + /* @internal */ + export type ObjectFlagsType = NullableType | ObjectType | UnionType | IntersectionType; + // Object types (TypeFlags.ObjectType) export interface ObjectType extends Type { objectFlags: ObjectFlags; @@ -4074,6 +4089,8 @@ namespace ts { export interface UnionOrIntersectionType extends Type { types: Type[]; // Constituent types /* @internal */ + objectFlags: ObjectFlags; + /* @internal */ propertyCache: SymbolTable; // Cache of resolved properties /* @internal */ resolvedProperties: Symbol[]; @@ -4088,8 +4105,6 @@ namespace ts { } export interface UnionType extends UnionOrIntersectionType { - /* @internal */ - primitiveTypesOnly: boolean; } export interface IntersectionType extends UnionOrIntersectionType { diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 29d2ebfa59e..aa2ebe3d60c 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -4515,7 +4515,7 @@ namespace ts { } export function getObjectFlags(type: Type): ObjectFlags { - return type.flags & TypeFlags.Object ? (type).objectFlags : 0; + return type.flags & TypeFlags.ObjectFlagsType ? (type).objectFlags : 0; } export function typeHasCallOrConstructSignatures(type: Type, checker: TypeChecker) { From ed8c81a5638c7d745cb8541137ad6990da045467 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Thu, 14 Feb 2019 14:56:22 -0800 Subject: [PATCH 065/149] Update lodash dependency (#29903) For security reasons --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 4f4f7db571d..f891f99be56 100644 --- a/package.json +++ b/package.json @@ -68,7 +68,7 @@ "gulp-sourcemaps": "latest", "istanbul": "latest", "jake": "latest", - "lodash": "4.17.10", + "lodash": "^4.17.11", "merge2": "latest", "minimist": "latest", "mkdirp": "latest", From 3e745e65cda9a0879741fe1ef6afcf395fced8e6 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Thu, 14 Feb 2019 15:22:19 -0800 Subject: [PATCH 066/149] Simplify flags propagation logic --- src/compiler/checker.ts | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index f76505ad4a5..579e27a848a 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -18354,7 +18354,6 @@ namespace ts { let propertiesTable: SymbolTable; let propertiesArray: Symbol[] = []; let spread: Type = emptyObjectType; - let propagatedFlags: ObjectFlags = 0; const contextualType = getApparentTypeOfContextualType(node); const contextualTypeHasPattern = contextualType && contextualType.pattern && @@ -18364,7 +18363,7 @@ namespace ts { const isInJavascript = isInJSFile(node) && !isInJsonFile(node); const enumTag = getJSDocEnumTag(node); const isJSObjectLiteral = !contextualType && isInJavascript && !enumTag; - let objectFlags: ObjectFlags = 0; + let objectFlags: ObjectFlags = freshObjectLiteralFlag; let patternWithComputedProperties = false; let hasComputedStringProperty = false; let hasComputedNumberProperty = false; @@ -18392,7 +18391,7 @@ namespace ts { checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl); } } - objectFlags |= getObjectFlags(type); + objectFlags |= getObjectFlags(type) & ObjectFlags.PropagatingFlags; const nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined; const prop = nameType ? createSymbol(SymbolFlags.Property | member.flags, getPropertyNameFromType(nameType), checkFlags | CheckFlags.Late) : @@ -18440,19 +18439,18 @@ namespace ts { checkExternalEmitHelpers(memberDecl, ExternalEmitHelpers.Assign); } if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags | ObjectFlags.FreshLiteral, inConstContext); + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext); propertiesArray = []; propertiesTable = createSymbolTable(); hasComputedStringProperty = false; hasComputedNumberProperty = false; - objectFlags = 0; } const type = checkExpression(memberDecl.expression); if (!isValidSpreadType(type)) { error(memberDecl, Diagnostics.Spread_types_may_only_be_created_from_object_types); return errorType; } - spread = getSpreadType(spread, type, node.symbol, propagatedFlags | ObjectFlags.FreshLiteral, inConstContext); + spread = getSpreadType(spread, type, node.symbol, objectFlags, inConstContext); offset = i + 1; continue; } @@ -18502,7 +18500,7 @@ namespace ts { if (spread !== emptyObjectType) { if (propertiesArray.length > 0) { - spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, propagatedFlags | ObjectFlags.FreshLiteral, inConstContext); + spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext); } return spread; } @@ -18513,7 +18511,7 @@ namespace ts { const stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, IndexKind.String) : undefined; const numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, IndexKind.Number) : undefined; const result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); - result.objectFlags |= ObjectFlags.ObjectLiteral | ObjectFlags.ContainsObjectLiteral | freshObjectLiteralFlag | objectFlags & ObjectFlags.PropagatingFlags; + result.objectFlags |= objectFlags | ObjectFlags.ObjectLiteral | ObjectFlags.ContainsObjectLiteral; if (isJSObjectLiteral) { result.objectFlags |= ObjectFlags.JSLiteral; } @@ -18523,7 +18521,6 @@ namespace ts { if (inDestructuringPattern) { result.pattern = node; } - propagatedFlags |= result.objectFlags & ObjectFlags.PropagatingFlags; return result; } } @@ -18710,7 +18707,7 @@ namespace ts { function createJsxAttributesType() { objectFlags |= freshObjectLiteralFlag; const result = createAnonymousType(attributes.symbol, attributesTable, emptyArray, emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); - result.objectFlags |= ObjectFlags.ObjectLiteral | ObjectFlags.ContainsObjectLiteral | objectFlags; + result.objectFlags |= objectFlags | ObjectFlags.ObjectLiteral | ObjectFlags.ContainsObjectLiteral; return result; } } From 8f52f21f0d13be285e7d2a9f8d7de1604c619d54 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Fri, 15 Feb 2019 06:22:17 -0800 Subject: [PATCH 067/149] Fix broken check in getUnionType (check was always true) --- src/compiler/checker.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 579e27a848a..718c7e541b9 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -9359,7 +9359,7 @@ namespace ts { } switch (unionReduction) { case UnionReduction.Literal: - if (includes & TypeFlags.StringOrNumberLiteralOrUnique | TypeFlags.BooleanLiteral) { + if (includes & (TypeFlags.Literal | TypeFlags.UniqueESSymbol)) { removeRedundantLiteralTypes(typeSet, includes); } break; From 7983813be0cfc1500f2f4c83793c784a3433e173 Mon Sep 17 00:00:00 2001 From: Ryan Cavanaugh Date: Fri, 15 Feb 2019 09:03:15 -0800 Subject: [PATCH 068/149] Use sha256 to hash file contents --- src/compiler/sys.ts | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts index 35e9a9ec35f..33283c93803 100644 --- a/src/compiler/sys.ts +++ b/src/compiler/sys.ts @@ -632,7 +632,7 @@ namespace ts { getModifiedTime, setModifiedTime, deleteFile, - createHash: _crypto ? createMD5HashUsingNativeCrypto : generateDjb2Hash, + createHash: _crypto ? createSHA256Hash : generateDjb2Hash, createSHA256Hash: _crypto ? createSHA256Hash : undefined, getMemoryUsage() { if (global.gc) { @@ -1125,12 +1125,6 @@ namespace ts { } } - function createMD5HashUsingNativeCrypto(data: string): string { - const hash = _crypto!.createHash("md5"); - hash.update(data); - return hash.digest("hex"); - } - function createSHA256Hash(data: string): string { const hash = _crypto!.createHash("sha256"); hash.update(data); From b93afffaf7cbb80749c9baefedeedca1610cf9ea Mon Sep 17 00:00:00 2001 From: Gabriela Araujo Britto Date: Fri, 15 Feb 2019 15:36:11 -0800 Subject: [PATCH 069/149] rename refactor tests --- .../refactorConvertToNamedParameters10.ts | 7 --- .../refactorConvertToNamedParameters19.ts | 24 ---------- .../refactorConvertToNamedParameters28.ts | 12 ----- .../refactorConvertToNamedParameters8.ts | 17 ------- ...ertToNamedParameters_allParamsOptional.ts} | 0 ...ConvertToNamedParameters_arrowFunction.ts} | 0 ...meters_arrowFunctionWithContextualType.ts} | 0 ...rConvertToNamedParameters_callComments.ts} | 0 ...rConvertToNamedParameters_callComments2.ts | 25 +++++++++++ ...orConvertToNamedParameters_chainedCall.ts} | 0 ...nvertToNamedParameters_classExpression.ts} | 0 ...tToNamedParameters_classTypeParameters.ts} | 0 ...orConvertToNamedParameters_constructor.ts} | 0 ...rConvertToNamedParameters_defaultClass.ts} | 0 ...actorConvertToNamedParameters_function.ts} | 0 ...vertToNamedParameters_functionComments.ts} | 0 ...ertToNamedParameters_functionComments1.ts} | 4 +- ...ertToNamedParameters_functionComments2.ts} | 17 ++++++- ...rtToNamedParameters_functionExpression.ts} | 0 ...NamedParameters_functionTypeParameters.ts} | 2 +- ...orConvertToNamedParameters_initializer.ts} | 0 ...ToNamedParameters_initializerInference.ts} | 0 ...efactorConvertToNamedParameters_method.ts} | 0 ...orConvertToNamedParameters_methodCalls.ts} | 0 ...onvertToNamedParameters_methodOverrides.ts | 45 +++++++++++++++++++ ...ctorConvertToNamedParameters_overloads.ts} | 0 ...onvertToNamedParameters_paramDecorator.ts} | 0 ...vertToNamedParameters_recursiveFunction.ts | 20 +++++++++ ...rtToNamedParameters_restParamInference.ts} | 0 ...rConvertToNamedParameters_staticMethod.ts} | 0 ...ctorConvertToNamedParameters_superCall.ts} | 0 ...ctorConvertToNamedParameters_thisParam.ts} | 2 +- ...onvertToNamedParameters_typedRestParam.ts} | 0 ...vertToNamedParameters_varArrowFunction.ts} | 0 34 files changed, 109 insertions(+), 66 deletions(-) delete mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters10.ts delete mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters19.ts delete mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters28.ts delete mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters8.ts rename tests/cases/fourslash/{refactorConvertToNamedParameters7.ts => refactorConvertToNamedParameters_allParamsOptional.ts} (100%) rename tests/cases/fourslash/{refactorConvertToNamedParameters12.ts => refactorConvertToNamedParameters_arrowFunction.ts} (100%) rename tests/cases/fourslash/{refactorConvertToNamedParameters22.ts => refactorConvertToNamedParameters_arrowFunctionWithContextualType.ts} (100%) rename tests/cases/fourslash/{refactorConvertToNamedParameters27.ts => refactorConvertToNamedParameters_callComments.ts} (100%) create mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters_callComments2.ts rename tests/cases/fourslash/{refactorConvertToNamedParameters20.ts => refactorConvertToNamedParameters_chainedCall.ts} (100%) rename tests/cases/fourslash/{refactorConvertToNamedParameters14.ts => refactorConvertToNamedParameters_classExpression.ts} (100%) rename tests/cases/fourslash/{refactorConvertToNamedParameters16.ts => refactorConvertToNamedParameters_classTypeParameters.ts} (100%) rename tests/cases/fourslash/{refactorConvertToNamedParameters2.ts => refactorConvertToNamedParameters_constructor.ts} (100%) rename tests/cases/fourslash/{refactorConvertToNamedParameters15.ts => refactorConvertToNamedParameters_defaultClass.ts} (100%) rename tests/cases/fourslash/{refactorConvertToNamedParameters.ts => refactorConvertToNamedParameters_function.ts} (100%) rename tests/cases/fourslash/{refactorConvertToNamedParameters26.ts => refactorConvertToNamedParameters_functionComments.ts} (100%) rename tests/cases/fourslash/{refactorConvertToNamedParameters25.ts => refactorConvertToNamedParameters_functionComments1.ts} (62%) rename tests/cases/fourslash/{refactorConvertToNamedParameters29.ts => refactorConvertToNamedParameters_functionComments2.ts} (56%) rename tests/cases/fourslash/{refactorConvertToNamedParameters11.ts => refactorConvertToNamedParameters_functionExpression.ts} (100%) rename tests/cases/fourslash/{refactorConvertToNamedParameters17.ts => refactorConvertToNamedParameters_functionTypeParameters.ts} (91%) rename tests/cases/fourslash/{refactorConvertToNamedParameters6.ts => refactorConvertToNamedParameters_initializer.ts} (100%) rename tests/cases/fourslash/{refactorConvertToNamedParameters4.ts => refactorConvertToNamedParameters_initializerInference.ts} (100%) rename tests/cases/fourslash/{refactorConvertToNamedParameters1.ts => refactorConvertToNamedParameters_method.ts} (100%) rename tests/cases/fourslash/{refactorConvertToNamedParameters5.ts => refactorConvertToNamedParameters_methodCalls.ts} (100%) create mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters_methodOverrides.ts rename tests/cases/fourslash/{refactorConvertToNamedParameters9.ts => refactorConvertToNamedParameters_overloads.ts} (100%) rename tests/cases/fourslash/{refactorConvertToNamedParameters30.ts => refactorConvertToNamedParameters_paramDecorator.ts} (100%) create mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters_recursiveFunction.ts rename tests/cases/fourslash/{refactorConvertToNamedParameters23.ts => refactorConvertToNamedParameters_restParamInference.ts} (100%) rename tests/cases/fourslash/{refactorConvertToNamedParameters3.ts => refactorConvertToNamedParameters_staticMethod.ts} (100%) rename tests/cases/fourslash/{refactorConvertToNamedParameters21.ts => refactorConvertToNamedParameters_superCall.ts} (100%) rename tests/cases/fourslash/{refactorConvertToNamedParameters18.ts => refactorConvertToNamedParameters_thisParam.ts} (92%) rename tests/cases/fourslash/{refactorConvertToNamedParameters24.ts => refactorConvertToNamedParameters_typedRestParam.ts} (100%) rename tests/cases/fourslash/{refactorConvertToNamedParameters13.ts => refactorConvertToNamedParameters_varArrowFunction.ts} (100%) diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters10.ts b/tests/cases/fourslash/refactorConvertToNamedParameters10.ts deleted file mode 100644 index 209a06d5bfa..00000000000 --- a/tests/cases/fourslash/refactorConvertToNamedParameters10.ts +++ /dev/null @@ -1,7 +0,0 @@ -/// - -////const { foo, bar } = { foo: /*a*/(a: number, b: number)/*b*/ => {}, bar: () => {} }; -////foo(1, 2); - -goTo.select("a", "b"); -verify.not.refactorAvailable("Convert to named parameters"); diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters19.ts b/tests/cases/fourslash/refactorConvertToNamedParameters19.ts deleted file mode 100644 index b635ce5e379..00000000000 --- a/tests/cases/fourslash/refactorConvertToNamedParameters19.ts +++ /dev/null @@ -1,24 +0,0 @@ -/// - -////class Foo { -//// /*a*/bar/*b*/(t: string, s: string): string { -//// return s + t; -//// } -////} -////var foo = {}; -////foo['bar']("a", "b"); -/// - -goTo.select("a", "b"); -edit.applyRefactor({ - refactorName: "Convert to named parameters", - actionName: "Convert to named parameters", - actionDescription: "Convert to named parameters", - newContent: `class Foo { - bar({ t, s }: { t: string; s: string; }): string { - return s + t; - } -} -var foo = {}; -foo['bar']("a", "b");` -}); \ No newline at end of file diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters28.ts b/tests/cases/fourslash/refactorConvertToNamedParameters28.ts deleted file mode 100644 index 8218ac65d80..00000000000 --- a/tests/cases/fourslash/refactorConvertToNamedParameters28.ts +++ /dev/null @@ -1,12 +0,0 @@ -/// - -////function /*a*/foo/*b*/(// comment -//// /** other comment */ a: number, b: number) { } - -goTo.select("a", "b"); -edit.applyRefactor({ - refactorName: "Convert to named parameters", - actionName: "Convert to named parameters", - actionDescription: "Convert to named parameters", - newContent: `function foo(// comment { a, b }: { /** other comment */ a: number; b: number; }) { }` -}); \ No newline at end of file diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters8.ts b/tests/cases/fourslash/refactorConvertToNamedParameters8.ts deleted file mode 100644 index 2c3d7de339f..00000000000 --- a/tests/cases/fourslash/refactorConvertToNamedParameters8.ts +++ /dev/null @@ -1,17 +0,0 @@ -/// - -////function f(/*a*/a: number, b = 1/*b*/) { -//// return b; -////} -////f(2); - -goTo.select("a", "b"); -edit.applyRefactor({ - refactorName: "Convert to named parameters", - actionName: "Convert to named parameters", - actionDescription: "Convert to named parameters", - newContent: `function f({ a, b = 1 }: { a: number; b?: number; }) { - return b; -} -f({ a: 2 });` -}); \ No newline at end of file diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters7.ts b/tests/cases/fourslash/refactorConvertToNamedParameters_allParamsOptional.ts similarity index 100% rename from tests/cases/fourslash/refactorConvertToNamedParameters7.ts rename to tests/cases/fourslash/refactorConvertToNamedParameters_allParamsOptional.ts diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters12.ts b/tests/cases/fourslash/refactorConvertToNamedParameters_arrowFunction.ts similarity index 100% rename from tests/cases/fourslash/refactorConvertToNamedParameters12.ts rename to tests/cases/fourslash/refactorConvertToNamedParameters_arrowFunction.ts diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters22.ts b/tests/cases/fourslash/refactorConvertToNamedParameters_arrowFunctionWithContextualType.ts similarity index 100% rename from tests/cases/fourslash/refactorConvertToNamedParameters22.ts rename to tests/cases/fourslash/refactorConvertToNamedParameters_arrowFunctionWithContextualType.ts diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters27.ts b/tests/cases/fourslash/refactorConvertToNamedParameters_callComments.ts similarity index 100% rename from tests/cases/fourslash/refactorConvertToNamedParameters27.ts rename to tests/cases/fourslash/refactorConvertToNamedParameters_callComments.ts diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters_callComments2.ts b/tests/cases/fourslash/refactorConvertToNamedParameters_callComments2.ts new file mode 100644 index 00000000000..e0a78b091fc --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToNamedParameters_callComments2.ts @@ -0,0 +1,25 @@ +/// + +////function /*a*/foo/*b*/(a: number, b: number, ...rest: number[]) { +//// return a + b; +////} +////foo( +//// /**a*/ +//// 1, +//// /**c*/ +//// 2, +//// /**e*/ +//// 3, +//// /**g*/ +//// 4); + +goTo.select("a", "b"); +edit.applyRefactor({ + refactorName: "Convert to named parameters", + actionName: "Convert to named parameters", + actionDescription: "Convert to named parameters", + newContent: `function foo({ a, b, rest = [] }: { a: number; b: number; rest?: number[]; }) { + return a + b; +} +foo({ a: /**a*/ 1, b: /**c*/ 2, rest: [/**e*/ 3, /**g*/ 4] });` +}); \ No newline at end of file diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters20.ts b/tests/cases/fourslash/refactorConvertToNamedParameters_chainedCall.ts similarity index 100% rename from tests/cases/fourslash/refactorConvertToNamedParameters20.ts rename to tests/cases/fourslash/refactorConvertToNamedParameters_chainedCall.ts diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters14.ts b/tests/cases/fourslash/refactorConvertToNamedParameters_classExpression.ts similarity index 100% rename from tests/cases/fourslash/refactorConvertToNamedParameters14.ts rename to tests/cases/fourslash/refactorConvertToNamedParameters_classExpression.ts diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters16.ts b/tests/cases/fourslash/refactorConvertToNamedParameters_classTypeParameters.ts similarity index 100% rename from tests/cases/fourslash/refactorConvertToNamedParameters16.ts rename to tests/cases/fourslash/refactorConvertToNamedParameters_classTypeParameters.ts diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters2.ts b/tests/cases/fourslash/refactorConvertToNamedParameters_constructor.ts similarity index 100% rename from tests/cases/fourslash/refactorConvertToNamedParameters2.ts rename to tests/cases/fourslash/refactorConvertToNamedParameters_constructor.ts diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters15.ts b/tests/cases/fourslash/refactorConvertToNamedParameters_defaultClass.ts similarity index 100% rename from tests/cases/fourslash/refactorConvertToNamedParameters15.ts rename to tests/cases/fourslash/refactorConvertToNamedParameters_defaultClass.ts diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters.ts b/tests/cases/fourslash/refactorConvertToNamedParameters_function.ts similarity index 100% rename from tests/cases/fourslash/refactorConvertToNamedParameters.ts rename to tests/cases/fourslash/refactorConvertToNamedParameters_function.ts diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters26.ts b/tests/cases/fourslash/refactorConvertToNamedParameters_functionComments.ts similarity index 100% rename from tests/cases/fourslash/refactorConvertToNamedParameters26.ts rename to tests/cases/fourslash/refactorConvertToNamedParameters_functionComments.ts diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters25.ts b/tests/cases/fourslash/refactorConvertToNamedParameters_functionComments1.ts similarity index 62% rename from tests/cases/fourslash/refactorConvertToNamedParameters25.ts rename to tests/cases/fourslash/refactorConvertToNamedParameters_functionComments1.ts index 1b51102f80e..e0d34c8fe65 100644 --- a/tests/cases/fourslash/refactorConvertToNamedParameters25.ts +++ b/tests/cases/fourslash/refactorConvertToNamedParameters_functionComments1.ts @@ -1,6 +1,6 @@ /// -////function /*a*/foo/*b*/(a: number, b: number) { /** missing */ +////function /*a*/foo/*b*/(a: number /** a */, b: number /** b */) { //// return a + b; ////} @@ -9,7 +9,7 @@ edit.applyRefactor({ refactorName: "Convert to named parameters", actionName: "Convert to named parameters", actionDescription: "Convert to named parameters", - newContent: `function foo({ a, b }: { a: number; b: number; }) { /** missing */ + newContent: `function foo({ a, b }: { a: number /** a */; b: number /** b */; }) { return a + b; }` }); \ No newline at end of file diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters29.ts b/tests/cases/fourslash/refactorConvertToNamedParameters_functionComments2.ts similarity index 56% rename from tests/cases/fourslash/refactorConvertToNamedParameters29.ts rename to tests/cases/fourslash/refactorConvertToNamedParameters_functionComments2.ts index 02582785944..923b49b4198 100644 --- a/tests/cases/fourslash/refactorConvertToNamedParameters29.ts +++ b/tests/cases/fourslash/refactorConvertToNamedParameters_functionComments2.ts @@ -1,7 +1,13 @@ /// ////function /*a*/foo/*b*/(// comment -//// a: number, b: number) { } +//// // a comment +//// a: number, +//// // b comment +//// b: number +////) { +//// return a + b; +////} goTo.select("a", "b"); edit.applyRefactor({ @@ -9,5 +15,12 @@ edit.applyRefactor({ actionName: "Convert to named parameters", actionDescription: "Convert to named parameters", newContent: `function foo(// comment - { a, b }: { a: number; b: number }) { }` +{ a, b }: { + // a comment + a: number; + // b comment + b: number; +}) { + return a + b; +}` }); \ No newline at end of file diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters11.ts b/tests/cases/fourslash/refactorConvertToNamedParameters_functionExpression.ts similarity index 100% rename from tests/cases/fourslash/refactorConvertToNamedParameters11.ts rename to tests/cases/fourslash/refactorConvertToNamedParameters_functionExpression.ts diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters17.ts b/tests/cases/fourslash/refactorConvertToNamedParameters_functionTypeParameters.ts similarity index 91% rename from tests/cases/fourslash/refactorConvertToNamedParameters17.ts rename to tests/cases/fourslash/refactorConvertToNamedParameters_functionTypeParameters.ts index 7888c33f4e2..a1597fdeed1 100644 --- a/tests/cases/fourslash/refactorConvertToNamedParameters17.ts +++ b/tests/cases/fourslash/refactorConvertToNamedParameters_functionTypeParameters.ts @@ -1,7 +1,7 @@ /// ////function foo(/*a*/t: T, s: S/*b*/) { -//// return s; +//// return s; ////} ////foo("a", "b"); diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters6.ts b/tests/cases/fourslash/refactorConvertToNamedParameters_initializer.ts similarity index 100% rename from tests/cases/fourslash/refactorConvertToNamedParameters6.ts rename to tests/cases/fourslash/refactorConvertToNamedParameters_initializer.ts diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters4.ts b/tests/cases/fourslash/refactorConvertToNamedParameters_initializerInference.ts similarity index 100% rename from tests/cases/fourslash/refactorConvertToNamedParameters4.ts rename to tests/cases/fourslash/refactorConvertToNamedParameters_initializerInference.ts diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters1.ts b/tests/cases/fourslash/refactorConvertToNamedParameters_method.ts similarity index 100% rename from tests/cases/fourslash/refactorConvertToNamedParameters1.ts rename to tests/cases/fourslash/refactorConvertToNamedParameters_method.ts diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters5.ts b/tests/cases/fourslash/refactorConvertToNamedParameters_methodCalls.ts similarity index 100% rename from tests/cases/fourslash/refactorConvertToNamedParameters5.ts rename to tests/cases/fourslash/refactorConvertToNamedParameters_methodCalls.ts diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters_methodOverrides.ts b/tests/cases/fourslash/refactorConvertToNamedParameters_methodOverrides.ts new file mode 100644 index 00000000000..b6daac17dd4 --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToNamedParameters_methodOverrides.ts @@ -0,0 +1,45 @@ +/// + +////class A { +//// /*a*/foo/*b*/(a: number, b: number) { } +////} +////class B extends A { +//// /*c*/foo/*d*/(c: number, d: number) { } +////} +////var a = new A(); +////a.foo(3, 4); +////var b = new B(); +////b.foo(5, 6); + +goTo.select("a", "b"); +edit.applyRefactor({ + refactorName: "Convert to named parameters", + actionName: "Convert to named parameters", + actionDescription: "Convert to named parameters", + newContent: `class A { + foo(a: number, b: number) { } +} +class B extends A { + foo(c: number, d: number) { } +} +var a = new A(); +a.foo(3, 4); +var b = new B(); +b.foo(5, 6);` +}); +goTo.select("c", "d"); +edit.applyRefactor({ + refactorName: "Convert to named parameters", + actionName: "Convert to named parameters", + actionDescription: "Convert to named parameters", + newContent: `class A { + foo(a: number, b: number) { } +} +class B extends A { + foo(c: number, d: number) { } +} +var a = new A(); +a.foo(3, 4); +var b = new B(); +b.foo(5, 6);` +}); diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters9.ts b/tests/cases/fourslash/refactorConvertToNamedParameters_overloads.ts similarity index 100% rename from tests/cases/fourslash/refactorConvertToNamedParameters9.ts rename to tests/cases/fourslash/refactorConvertToNamedParameters_overloads.ts diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters30.ts b/tests/cases/fourslash/refactorConvertToNamedParameters_paramDecorator.ts similarity index 100% rename from tests/cases/fourslash/refactorConvertToNamedParameters30.ts rename to tests/cases/fourslash/refactorConvertToNamedParameters_paramDecorator.ts diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters_recursiveFunction.ts b/tests/cases/fourslash/refactorConvertToNamedParameters_recursiveFunction.ts new file mode 100644 index 00000000000..d1513cb7bf0 --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToNamedParameters_recursiveFunction.ts @@ -0,0 +1,20 @@ +/// + +////const f = function foo(/*a*/a: number, b: number/*b*/) { +//// foo(1, 2); +////} +////function foo(a: number, b: number) { } +////foo(3, 4); + + +goTo.select("a", "b"); +edit.applyRefactor({ + refactorName: "Convert to named parameters", + actionName: "Convert to named parameters", + actionDescription: "Convert to named parameters", + newContent: `const f = function foo({ a, b }: { a: number; b: number; }) { + foo({ a: 1, b: 2 }); +} +function foo(a: number, b: number) { } +foo(3, 4);` +}); \ No newline at end of file diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters23.ts b/tests/cases/fourslash/refactorConvertToNamedParameters_restParamInference.ts similarity index 100% rename from tests/cases/fourslash/refactorConvertToNamedParameters23.ts rename to tests/cases/fourslash/refactorConvertToNamedParameters_restParamInference.ts diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters3.ts b/tests/cases/fourslash/refactorConvertToNamedParameters_staticMethod.ts similarity index 100% rename from tests/cases/fourslash/refactorConvertToNamedParameters3.ts rename to tests/cases/fourslash/refactorConvertToNamedParameters_staticMethod.ts diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters21.ts b/tests/cases/fourslash/refactorConvertToNamedParameters_superCall.ts similarity index 100% rename from tests/cases/fourslash/refactorConvertToNamedParameters21.ts rename to tests/cases/fourslash/refactorConvertToNamedParameters_superCall.ts diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters18.ts b/tests/cases/fourslash/refactorConvertToNamedParameters_thisParam.ts similarity index 92% rename from tests/cases/fourslash/refactorConvertToNamedParameters18.ts rename to tests/cases/fourslash/refactorConvertToNamedParameters_thisParam.ts index 069182e20e5..e4a96bc7bf1 100644 --- a/tests/cases/fourslash/refactorConvertToNamedParameters18.ts +++ b/tests/cases/fourslash/refactorConvertToNamedParameters_thisParam.ts @@ -1,7 +1,7 @@ /// ////function foo(this: void, /*a*/t: string, s: string/*b*/) { -//// return s; +//// return s; ////} ////foo("a", "b"); diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters24.ts b/tests/cases/fourslash/refactorConvertToNamedParameters_typedRestParam.ts similarity index 100% rename from tests/cases/fourslash/refactorConvertToNamedParameters24.ts rename to tests/cases/fourslash/refactorConvertToNamedParameters_typedRestParam.ts diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters13.ts b/tests/cases/fourslash/refactorConvertToNamedParameters_varArrowFunction.ts similarity index 100% rename from tests/cases/fourslash/refactorConvertToNamedParameters13.ts rename to tests/cases/fourslash/refactorConvertToNamedParameters_varArrowFunction.ts From eef3da5b6bf9372ea2899e0cd4fadcb33e0948cd Mon Sep 17 00:00:00 2001 From: Gabriela Araujo Britto Date: Fri, 15 Feb 2019 15:38:10 -0800 Subject: [PATCH 070/149] create new ConfigurableStart and ConfigurableEnd options and rename them --- src/services/organizeImports.ts | 4 +- .../refactors/convertToNamedParameters.ts | 8 ++- src/services/textChanges.ts | 69 ++++++++++++------- .../unittests/services/textChanges.ts | 26 +++---- 4 files changed, 65 insertions(+), 42 deletions(-) diff --git a/src/services/organizeImports.ts b/src/services/organizeImports.ts index 157ba98e262..8096ffa4ad2 100644 --- a/src/services/organizeImports.ts +++ b/src/services/organizeImports.ts @@ -68,8 +68,8 @@ namespace ts.OrganizeImports { else { // Note: Delete the surrounding trivia because it will have been retained in newImportDecls. changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, { - useNonAdjustedStartPosition: true, // Leave header comment in place - useNonAdjustedEndPosition: false, + startPosition: textChanges.LeadingTriviaOption.Exclude, // Leave header comment in place + endPosition: textChanges.TrailingTriviaOption.Include, suffix: getNewLineOrDefaultFromHost(host, formatContext.options), }); } diff --git a/src/services/refactors/convertToNamedParameters.ts b/src/services/refactors/convertToNamedParameters.ts index 6e5881a31f6..cf348bd9e73 100644 --- a/src/services/refactors/convertToNamedParameters.ts +++ b/src/services/refactors/convertToNamedParameters.ts @@ -47,7 +47,13 @@ namespace ts.refactor.convertToNamedParameters { first(functionDeclaration.parameters), last(functionDeclaration.parameters), newParamDeclaration, - { joiner: ", ", indentation: 0 }); // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter + { joiner: ", ", + // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter + indentation: 0, + startPosition: textChanges.LeadingTriviaOption.IncludeAll, + endPosition: textChanges.TrailingTriviaOption.Include + }); + const functionCalls = groupedReferences.calls; forEach(functionCalls, call => { diff --git a/src/services/textChanges.ts b/src/services/textChanges.ts index 4689e18508c..546fddaca14 100644 --- a/src/services/textChanges.ts +++ b/src/services/textChanges.ts @@ -28,17 +28,32 @@ namespace ts.textChanges { } export interface ConfigurableStart { - /** True to use getStart() (NB, not getFullStart()) without adjustment. */ - useNonAdjustedStartPosition?: boolean; + startPosition?: LeadingTriviaOption; } export interface ConfigurableEnd { /** True to use getEnd() without adjustment. */ - useNonAdjustedEndPosition?: boolean; + endPosition?: TrailingTriviaOption; } - export enum Position { - FullStart, - Start + export enum LeadingTriviaOption { + /** Exclude all leading trivia (use getStart()) */ + Exclude, + /** Include leading trivia (default behavior) */ + Include, + /** Include leading trivia and, + * if there are no line breaks between the node and the previous token, + * include all trivia between the node and the previous token + */ + IncludeAll, + } + + export enum TrailingTriviaOption { + /** Exclude all leading trivia (use getEnd()) */ + Exclude, + /** TODO (default behavior) */ + IncludeIfLineBreak, + /** Include trailing trivia */ + Include, } function skipWhitespacesAndLineBreaks(text: string, start: number) { @@ -73,8 +88,8 @@ namespace ts.textChanges { export interface ConfigurableStartEnd extends ConfigurableStart, ConfigurableEnd {} export const useNonAdjustedPositions: ConfigurableStartEnd = { - useNonAdjustedStartPosition: true, - useNonAdjustedEndPosition: true, + startPosition: LeadingTriviaOption.Exclude, + endPosition: TrailingTriviaOption.Exclude, }; export interface InsertNodeOptions { @@ -143,11 +158,12 @@ namespace ts.textChanges { } function getAdjustedRange(sourceFile: SourceFile, startNode: Node, endNode: Node, options: ConfigurableStartEnd): TextRange { - return { pos: getAdjustedStartPosition(sourceFile, startNode, options, Position.Start), end: getAdjustedEndPosition(sourceFile, endNode, options) }; + return { pos: getAdjustedStartPosition(sourceFile, startNode, options), end: getAdjustedEndPosition(sourceFile, endNode, options) }; } - function getAdjustedStartPosition(sourceFile: SourceFile, node: Node, options: ConfigurableStart, position: Position) { - if (options.useNonAdjustedStartPosition) { + function getAdjustedStartPosition(sourceFile: SourceFile, node: Node, options: ConfigurableStart) { + const { startPosition } = options; + if (startPosition === LeadingTriviaOption.Exclude) { return node.getStart(sourceFile); } const fullStart = node.getFullStart(); @@ -165,7 +181,7 @@ namespace ts.textChanges { // fullstart // when b is replaced - we usually want to keep the leading trvia // when b is deleted - we delete it - return position === Position.Start ? start : fullStart; + return startPosition === LeadingTriviaOption.IncludeAll ? fullStart : start; } // get start position of the line following the line that contains fullstart position // (but only if the fullstart isn't the very beginning of the file) @@ -178,11 +194,12 @@ namespace ts.textChanges { function getAdjustedEndPosition(sourceFile: SourceFile, node: Node, options: ConfigurableEnd) { const { end } = node; - if (options.useNonAdjustedEndPosition || isExpression(node)) { + const { endPosition } = options; + if (endPosition === TrailingTriviaOption.Exclude || isExpression(node)) { return end; } const newEnd = skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true); - return newEnd !== end && isLineBreak(sourceFile.text.charCodeAt(newEnd - 1)) + return newEnd !== end && (endPosition === TrailingTriviaOption.Include || isLineBreak(sourceFile.text.charCodeAt(newEnd - 1))) ? newEnd : end; } @@ -240,15 +257,15 @@ namespace ts.textChanges { this.deleteRange(sourceFile, { pos: modifier.getStart(sourceFile), end: skipTrivia(sourceFile.text, modifier.end, /*stopAfterLineBreak*/ true) }); } - public deleteNodeRange(sourceFile: SourceFile, startNode: Node, endNode: Node, options: ConfigurableStartEnd = {}): void { - const startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart); + public deleteNodeRange(sourceFile: SourceFile, startNode: Node, endNode: Node, options: ConfigurableStartEnd = { startPosition: LeadingTriviaOption.IncludeAll }): void { + const startPosition = getAdjustedStartPosition(sourceFile, startNode, options); const endPosition = getAdjustedEndPosition(sourceFile, endNode, options); this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); } - public deleteNodeRangeExcludingEnd(sourceFile: SourceFile, startNode: Node, afterEndNode: Node | undefined, options: ConfigurableStartEnd = {}): void { - const startPosition = getAdjustedStartPosition(sourceFile, startNode, options, Position.FullStart); - const endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options, Position.FullStart); + public deleteNodeRangeExcludingEnd(sourceFile: SourceFile, startNode: Node, afterEndNode: Node | undefined, options: ConfigurableStartEnd = { startPosition: LeadingTriviaOption.IncludeAll }): void { + const startPosition = getAdjustedStartPosition(sourceFile, startNode, options); + const endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options); this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); } @@ -307,7 +324,7 @@ namespace ts.textChanges { } public insertNodeBefore(sourceFile: SourceFile, before: Node, newNode: Node, blankLineBetween = false): void { - this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, {}, Position.Start), newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween)); + this.insertNodeAt(sourceFile, getAdjustedStartPosition(sourceFile, before, {}), newNode, this.getOptionsForInsertNodeBefore(before, blankLineBetween)); } public insertModifierBefore(sourceFile: SourceFile, modifier: SyntaxKind, before: Node): void { @@ -427,7 +444,7 @@ namespace ts.textChanges { } public insertNodeAtEndOfScope(sourceFile: SourceFile, scope: Node, newNode: Node): void { - const pos = getAdjustedStartPosition(sourceFile, scope.getLastToken()!, {}, Position.Start); + const pos = getAdjustedStartPosition(sourceFile, scope.getLastToken()!, {}); this.insertNodeAt(sourceFile, pos, newNode, { prefix: isLineBreak(sourceFile.text.charCodeAt(scope.getLastToken()!.pos)) ? this.newLineCharacter : this.newLineCharacter + this.newLineCharacter, suffix: this.newLineCharacter @@ -736,7 +753,7 @@ namespace ts.textChanges { // find first non-whitespace position in the leading trivia of the node function startPositionToDeleteNodeInList(sourceFile: SourceFile, node: Node): number { - return skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, {}, Position.FullStart), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); + return skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, { startPosition: LeadingTriviaOption.IncludeAll }), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); } function getClassOrObjectBraceEnds(cls: ClassLikeDeclaration | InterfaceDeclaration | ObjectLiteralExpression, sourceFile: SourceFile): [number, number] { @@ -1090,7 +1107,7 @@ namespace ts.textChanges { case SyntaxKind.ImportDeclaration: deleteNode(changes, sourceFile, node, // For first import, leave header comment in place - node === sourceFile.imports[0].parent ? { useNonAdjustedStartPosition: true, useNonAdjustedEndPosition: false } : undefined); + node === sourceFile.imports[0].parent ? { startPosition: LeadingTriviaOption.Exclude, endPosition: TrailingTriviaOption.IncludeIfLineBreak } : undefined); break; case SyntaxKind.BindingElement: @@ -1134,7 +1151,7 @@ namespace ts.textChanges { deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); } else { - deleteNode(changes, sourceFile, node, node.kind === SyntaxKind.SemicolonToken ? { useNonAdjustedEndPosition: true } : undefined); + deleteNode(changes, sourceFile, node, node.kind === SyntaxKind.SemicolonToken ? { endPosition: TrailingTriviaOption.Exclude } : undefined); } } } @@ -1213,8 +1230,8 @@ namespace ts.textChanges { /** Warning: This deletes comments too. See `copyComments` in `convertFunctionToEs6Class`. */ // Exported for tests only! (TODO: improve tests to not need this) - export function deleteNode(changes: ChangeTracker, sourceFile: SourceFile, node: Node, options: ConfigurableStartEnd = {}): void { - const startPosition = getAdjustedStartPosition(sourceFile, node, options, Position.FullStart); + export function deleteNode(changes: ChangeTracker, sourceFile: SourceFile, node: Node, options: ConfigurableStartEnd = { startPosition: LeadingTriviaOption.IncludeAll }): void { + const startPosition = getAdjustedStartPosition(sourceFile, node, options); const endPosition = getAdjustedEndPosition(sourceFile, node, options); changes.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); } diff --git a/src/testRunner/unittests/services/textChanges.ts b/src/testRunner/unittests/services/textChanges.ts index de92efafbeb..f9e03a578de 100644 --- a/src/testRunner/unittests/services/textChanges.ts +++ b/src/testRunner/unittests/services/textChanges.ts @@ -140,13 +140,13 @@ var z = 3; // comment 4 deleteNode(changeTracker, sourceFile, findVariableStatementContaining("y", sourceFile)); }); runSingleFileTest("deleteNode2", /*placeOpenBraceOnNewLineForFunctions*/ false, text, /*validateNodes*/ false, (sourceFile, changeTracker) => { - deleteNode(changeTracker, sourceFile, findVariableStatementContaining("y", sourceFile), { useNonAdjustedStartPosition: true }); + deleteNode(changeTracker, sourceFile, findVariableStatementContaining("y", sourceFile), { startPosition: textChanges.LeadingTriviaOption.Exclude }); }); runSingleFileTest("deleteNode3", /*placeOpenBraceOnNewLineForFunctions*/ false, text, /*validateNodes*/ false, (sourceFile, changeTracker) => { - deleteNode(changeTracker, sourceFile, findVariableStatementContaining("y", sourceFile), { useNonAdjustedEndPosition: true }); + deleteNode(changeTracker, sourceFile, findVariableStatementContaining("y", sourceFile), { endPosition: textChanges.TrailingTriviaOption.Exclude }); }); runSingleFileTest("deleteNode4", /*placeOpenBraceOnNewLineForFunctions*/ false, text, /*validateNodes*/ false, (sourceFile, changeTracker) => { - deleteNode(changeTracker, sourceFile, findVariableStatementContaining("y", sourceFile), { useNonAdjustedStartPosition: true, useNonAdjustedEndPosition: true }); + deleteNode(changeTracker, sourceFile, findVariableStatementContaining("y", sourceFile), { startPosition: textChanges.LeadingTriviaOption.Exclude, endPosition: textChanges.TrailingTriviaOption.Exclude }); }); runSingleFileTest("deleteNode5", /*placeOpenBraceOnNewLineForFunctions*/ false, text, /*validateNodes*/ false, (sourceFile, changeTracker) => { deleteNode(changeTracker, sourceFile, findVariableStatementContaining("x", sourceFile)); @@ -167,15 +167,15 @@ var a = 4; // comment 7 }); runSingleFileTest("deleteNodeRange2", /*placeOpenBraceOnNewLineForFunctions*/ false, text, /*validateNodes*/ false, (sourceFile, changeTracker) => { changeTracker.deleteNodeRange(sourceFile, findVariableStatementContaining("y", sourceFile), findVariableStatementContaining("z", sourceFile), - { useNonAdjustedStartPosition: true }); + { startPosition: textChanges.LeadingTriviaOption.Exclude }); }); runSingleFileTest("deleteNodeRange3", /*placeOpenBraceOnNewLineForFunctions*/ false, text, /*validateNodes*/ false, (sourceFile, changeTracker) => { changeTracker.deleteNodeRange(sourceFile, findVariableStatementContaining("y", sourceFile), findVariableStatementContaining("z", sourceFile), - { useNonAdjustedEndPosition: true }); + { endPosition: textChanges.TrailingTriviaOption.Exclude }); }); runSingleFileTest("deleteNodeRange4", /*placeOpenBraceOnNewLineForFunctions*/ false, text, /*validateNodes*/ false, (sourceFile, changeTracker) => { changeTracker.deleteNodeRange(sourceFile, findVariableStatementContaining("y", sourceFile), findVariableStatementContaining("z", sourceFile), - { useNonAdjustedStartPosition: true, useNonAdjustedEndPosition: true }); + { startPosition: textChanges.LeadingTriviaOption.Exclude, endPosition: textChanges.TrailingTriviaOption.Exclude }); }); } function createTestVariableDeclaration(name: string) { @@ -254,16 +254,16 @@ var a = 4; // comment 7`; changeTracker.replaceNode(sourceFile, findVariableStatementContaining("y", sourceFile), createTestClass(), { suffix: newLineCharacter }); }); runSingleFileTest("replaceNode2", /*placeOpenBraceOnNewLineForFunctions*/ true, text, /*validateNodes*/ true, (sourceFile, changeTracker) => { - changeTracker.replaceNode(sourceFile, findVariableStatementContaining("y", sourceFile), createTestClass(), { useNonAdjustedStartPosition: true, suffix: newLineCharacter, prefix: newLineCharacter }); + changeTracker.replaceNode(sourceFile, findVariableStatementContaining("y", sourceFile), createTestClass(), { startPosition: textChanges.LeadingTriviaOption.Exclude, suffix: newLineCharacter, prefix: newLineCharacter }); }); runSingleFileTest("replaceNode3", /*placeOpenBraceOnNewLineForFunctions*/ true, text, /*validateNodes*/ true, (sourceFile, changeTracker) => { - changeTracker.replaceNode(sourceFile, findVariableStatementContaining("y", sourceFile), createTestClass(), { useNonAdjustedEndPosition: true, suffix: newLineCharacter }); + changeTracker.replaceNode(sourceFile, findVariableStatementContaining("y", sourceFile), createTestClass(), { endPosition: textChanges.TrailingTriviaOption.Exclude, suffix: newLineCharacter }); }); runSingleFileTest("replaceNode4", /*placeOpenBraceOnNewLineForFunctions*/ true, text, /*validateNodes*/ true, (sourceFile, changeTracker) => { - changeTracker.replaceNode(sourceFile, findVariableStatementContaining("y", sourceFile), createTestClass(), { useNonAdjustedStartPosition: true, useNonAdjustedEndPosition: true }); + changeTracker.replaceNode(sourceFile, findVariableStatementContaining("y", sourceFile), createTestClass(), { startPosition: textChanges.LeadingTriviaOption.Exclude, endPosition: textChanges.TrailingTriviaOption.Exclude }); }); runSingleFileTest("replaceNode5", /*placeOpenBraceOnNewLineForFunctions*/ true, text, /*validateNodes*/ true, (sourceFile, changeTracker) => { - changeTracker.replaceNode(sourceFile, findVariableStatementContaining("x", sourceFile), createTestClass(), { useNonAdjustedStartPosition: true, useNonAdjustedEndPosition: true }); + changeTracker.replaceNode(sourceFile, findVariableStatementContaining("x", sourceFile), createTestClass(), { startPosition: textChanges.LeadingTriviaOption.Exclude, endPosition: textChanges.TrailingTriviaOption.Exclude }); }); } { @@ -279,13 +279,13 @@ var a = 4; // comment 7`; changeTracker.replaceNodeRange(sourceFile, findVariableStatementContaining("y", sourceFile), findVariableStatementContaining("z", sourceFile), createTestClass(), { suffix: newLineCharacter }); }); runSingleFileTest("replaceNodeRange2", /*placeOpenBraceOnNewLineForFunctions*/ true, text, /*validateNodes*/ true, (sourceFile, changeTracker) => { - changeTracker.replaceNodeRange(sourceFile, findVariableStatementContaining("y", sourceFile), findVariableStatementContaining("z", sourceFile), createTestClass(), { useNonAdjustedStartPosition: true, suffix: newLineCharacter, prefix: newLineCharacter }); + changeTracker.replaceNodeRange(sourceFile, findVariableStatementContaining("y", sourceFile), findVariableStatementContaining("z", sourceFile), createTestClass(), { startPosition: textChanges.LeadingTriviaOption.Exclude, suffix: newLineCharacter, prefix: newLineCharacter }); }); runSingleFileTest("replaceNodeRange3", /*placeOpenBraceOnNewLineForFunctions*/ true, text, /*validateNodes*/ true, (sourceFile, changeTracker) => { - changeTracker.replaceNodeRange(sourceFile, findVariableStatementContaining("y", sourceFile), findVariableStatementContaining("z", sourceFile), createTestClass(), { useNonAdjustedEndPosition: true, suffix: newLineCharacter }); + changeTracker.replaceNodeRange(sourceFile, findVariableStatementContaining("y", sourceFile), findVariableStatementContaining("z", sourceFile), createTestClass(), { endPosition: textChanges.TrailingTriviaOption.Exclude, suffix: newLineCharacter }); }); runSingleFileTest("replaceNodeRange4", /*placeOpenBraceOnNewLineForFunctions*/ true, text, /*validateNodes*/ true, (sourceFile, changeTracker) => { - changeTracker.replaceNodeRange(sourceFile, findVariableStatementContaining("y", sourceFile), findVariableStatementContaining("z", sourceFile), createTestClass(), { useNonAdjustedStartPosition: true, useNonAdjustedEndPosition: true }); + changeTracker.replaceNodeRange(sourceFile, findVariableStatementContaining("y", sourceFile), findVariableStatementContaining("z", sourceFile), createTestClass(), { startPosition: textChanges.LeadingTriviaOption.Exclude, endPosition: textChanges.TrailingTriviaOption.Exclude }); }); } { From b6c8382c78596f1b90c6b89dc6368c163b6fa9f6 Mon Sep 17 00:00:00 2001 From: Gabriela Araujo Britto Date: Fri, 15 Feb 2019 15:51:20 -0800 Subject: [PATCH 071/149] replace argument list instead of whole call when refactoring --- .../refactors/convertToNamedParameters.ts | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/src/services/refactors/convertToNamedParameters.ts b/src/services/refactors/convertToNamedParameters.ts index cf348bd9e73..dc8043ddfa9 100644 --- a/src/services/refactors/convertToNamedParameters.ts +++ b/src/services/refactors/convertToNamedParameters.ts @@ -59,18 +59,15 @@ namespace ts.refactor.convertToNamedParameters { forEach(functionCalls, call => { if (call.arguments && call.arguments.length) { const newArgument = getSynthesizedDeepClone(createNewArguments(functionDeclaration, call.arguments), /*includeTrivia*/ true); - const newCall = updateCallArguments(call, createNodeArray([newArgument])); - suppressLeadingAndTrailingTrivia(newCall, /*recursive*/ false); - changes.replaceNode(getSourceFileOfNode(call), call, newCall); + changes.replaceNodeRange( + getSourceFileOfNode(call), + first(call.arguments), + last(call.arguments), + newArgument, + { startPosition: textChanges.LeadingTriviaOption.IncludeAll, endPosition: textChanges.TrailingTriviaOption.Include }); }}); } - function updateCallArguments(call: CallExpression | NewExpression, args: NodeArray) { - const newCall = getSynthesizedClone(call); - newCall.arguments = args; - return updateNode(newCall, call); - } - function getGroupedReferences(functionNames: Node[], program: Program, cancellationToken: CancellationToken): GroupedReferences { const functionRefs = flatMap(functionNames, name => FindAllReferences.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken)); const groupedReferences = groupReferences(functionRefs); From a7730461816c5423b66b27b074a5983402322442 Mon Sep 17 00:00:00 2001 From: Gabriela Araujo Britto Date: Fri, 15 Feb 2019 16:48:54 -0800 Subject: [PATCH 072/149] copy argument comments to property --- src/services/refactors/convertToNamedParameters.ts | 6 +++--- .../refactorConvertToNamedParameters_callComments.ts | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/services/refactors/convertToNamedParameters.ts b/src/services/refactors/convertToNamedParameters.ts index dc8043ddfa9..8b966ad0ab2 100644 --- a/src/services/refactors/convertToNamedParameters.ts +++ b/src/services/refactors/convertToNamedParameters.ts @@ -58,7 +58,7 @@ namespace ts.refactor.convertToNamedParameters { const functionCalls = groupedReferences.calls; forEach(functionCalls, call => { if (call.arguments && call.arguments.length) { - const newArgument = getSynthesizedDeepClone(createNewArguments(functionDeclaration, call.arguments), /*includeTrivia*/ true); + const newArgument = getSynthesizedDeepClone(createNewArgument(functionDeclaration, call.arguments), /*includeTrivia*/ true); changes.replaceNodeRange( getSourceFileOfNode(call), first(call.arguments), @@ -215,14 +215,14 @@ namespace ts.refactor.convertToNamedParameters { return parameters; } - function createNewArguments(functionDeclaration: ValidFunctionDeclaration, args: NodeArray): ObjectLiteralExpression { + function createNewArgument(functionDeclaration: ValidFunctionDeclaration, args: NodeArray): ObjectLiteralExpression { const parameters = getRefactorableParameters(functionDeclaration.parameters); const hasRestParameter = isRestParameter(last(parameters)); const nonRestArguments = hasRestParameter ? args.slice(0, parameters.length - 1) : args; const properties = map(nonRestArguments, (arg, i) => { const property = createPropertyAssignment(getParameterName(parameters[i]), arg); suppressLeadingAndTrailingTrivia(property.initializer); - copyComments(arg, property.initializer); + copyComments(arg, property); return property; }); diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters_callComments.ts b/tests/cases/fourslash/refactorConvertToNamedParameters_callComments.ts index 5bcda77fe0b..6fb06fe938b 100644 --- a/tests/cases/fourslash/refactorConvertToNamedParameters_callComments.ts +++ b/tests/cases/fourslash/refactorConvertToNamedParameters_callComments.ts @@ -13,5 +13,5 @@ edit.applyRefactor({ newContent: `function foo({ a, b, rest = [] }: { a: number; b: number; rest?: number[]; }) { return a + b; } -foo({ a: /**a*/ 1 /**b*/, b: /**c*/ 2 /**d*/, rest: [/**e*/ 3 /**f*/, /**g*/ 4 /**h*/] });` +foo({ /**a*/ a: 1 /**b*/, /**c*/ b: 2 /**d*/, rest: [/**e*/ 3 /**f*/, /**g*/ 4 /**h*/] });` }); \ No newline at end of file From 540aeb6073dec5e1669f84468c7e76310895249a Mon Sep 17 00:00:00 2001 From: Tom J Date: Sun, 17 Feb 2019 18:28:32 +0000 Subject: [PATCH 073/149] update docs: dated build cmd MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Hopefully I didn't miss something obvious. Running `gulp build` as suggested causes the following: ``` $ gulp build [18:26:11] Using gulpfile ~/git/TypeScript/Gulpfile.js [18:26:11] Task never defined: build [18:26:11] To list available tasks, try running: gulp --tasks ``` ``` $ gulp --tasks gulp --tasks [18:21:26] Tasks for ~/git/TypeScript/Gulpfile.js [18:21:26] ├── lib Builds the library targets ... ... [18:21:27] ├─┬ default Runs 'local' [18:21:27] │ └─┬ [18:21:27] │ └─┬ local [18:21:27] │ └─┬ [18:21:27] │ ├── buildFoldStart [18:21:27] │ ├─┬ [18:21:27] │ │ ├── generateLibs [18:21:27] │ │ └─┬ [18:21:27] │ │ ├── buildScripts [18:21:27] │ │ └── generateDiagnostics [18:21:27] │ ├─┬ [18:21:27] │ │ ├── localize [18:21:27] │ │ ├── buildTsc [18:21:27] │ │ ├── buildServer [18:21:27] │ │ ├─┬ [18:21:27] │ │ │ ├── flattenServicesConfig [18:21:27] │ │ │ ├── buildTypescriptServicesOut [18:21:27] │ │ │ ├── createTypescriptServicesJs [18:21:27] │ │ │ ├── createTypescriptServicesDts [18:21:27] │ │ │ ├── createTypescriptJs [18:21:27] │ │ │ ├── createTypescriptDts [18:21:27] │ │ │ └── createTypescriptStandaloneDts [18:21:27] │ │ └─┬ [18:21:27] │ │ ├── flattenTsServerProject [18:21:27] │ │ ├── buildServerLibraryOut [18:21:27] │ │ ├── createServerLibraryJs [18:21:27] │ │ └── createServerLibraryDts [18:21:27] │ └── buildFoldEnd [18:21:27] └── help Prints the top-level tasks. ``` The default task seems to do something useful: ``` $ gulp [18:21:49] Using gulpfile ~/git/TypeScript/Gulpfile.js [18:21:49] Starting 'default'... [18:21:49] Starting 'local'... [18:21:49] Starting 'buildFoldStart'... [18:21:49] Finished 'buildFoldStart' after 726 μs [18:21:49] Starting 'generateLibs'... [18:21:49] Starting 'buildScripts'... [18:21:49] Finished 'generateLibs' after 207 ms [18:21:49] Finished 'buildScripts' after 686 ms [18:21:49] Starting 'generateDiagnostics'... [18:21:49] Finished 'generateDiagnostics' after 700 μs [18:21:49] Starting 'localize'... [18:21:49] Starting 'buildTsc'... [18:21:49] Starting 'buildServer'... [18:21:49] > /usr/bin/node scripts/generateLocalizedDiagnosticMessages.js src/loc/lcl built/local src/compiler/diagnosticMessages.generated.json [18:21:49] Starting 'flattenServicesConfig'... [18:21:49] Starting 'flattenTsServerProject'... [18:21:49] Finished 'flattenServicesConfig' after 54 ms [18:21:49] Starting 'buildTypescriptServicesOut'... [18:21:49] Finished 'flattenTsServerProject' after 54 ms [18:21:49] Starting 'buildServerLibraryOut'... [18:21:53] Finished 'localize' after 3.38 s [18:23:17] Finished 'buildTsc' after 1.45 min [18:23:17] Finished 'buildServer' after 1.45 min [18:23:17] Finished 'buildTypescriptServicesOut' after 1.45 min [18:23:17] Starting 'createTypescriptServicesJs'... [18:23:17] Finished 'buildServerLibraryOut' after 1.45 min [18:23:17] Starting 'createServerLibraryJs'... [18:23:17] Finished 'createServerLibraryJs' after 635 ms [18:23:17] Starting 'createServerLibraryDts'... [18:23:18] Finished 'createTypescriptServicesJs' after 642 ms [18:23:18] Starting 'createTypescriptServicesDts'... [18:23:18] Finished 'createTypescriptServicesDts' after 20 ms [18:23:18] Starting 'createTypescriptJs'... [18:23:18] Finished 'createServerLibraryDts' after 30 ms [18:23:18] Finished 'createTypescriptJs' after 260 ms [18:23:18] Starting 'createTypescriptDts'... [18:23:18] Finished 'createTypescriptDts' after 4.47 ms [18:23:18] Starting 'createTypescriptStandaloneDts'... [18:23:18] Finished 'createTypescriptStandaloneDts' after 5.59 ms [18:23:18] Starting 'buildFoldEnd'... [18:23:18] Finished 'buildFoldEnd' after 350 μs [18:23:18] Finished 'local' after 1.48 min [18:23:18] Finished 'default' after 1.48 min ``` I'm I'm guessing wrongly, please reject & correct the docs to whatever the right way to run builds is. --- CONTRIBUTING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 980f84a3800..31cfb858089 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -55,7 +55,7 @@ The TypeScript repository is relatively large. To save some time, you might want ### Using local builds -Run `gulp build` to build a version of the compiler/language service that reflects changes you've made. You can then run `node /built/local/tsc.js` in place of `tsc` in your project. For example, to run `tsc --watch` from within the root of the repository on a file called `test.ts`, you can run `node ./built/local/tsc.js --watch test.ts`. +Run `gulp` to build a version of the compiler/language service that reflects changes you've made. You can then run `node /built/local/tsc.js` in place of `tsc` in your project. For example, to run `tsc --watch` from within the root of the repository on a file called `test.ts`, you can run `node ./built/local/tsc.js --watch test.ts`. ## Contributing bug fixes From 059fd2d42eef48cafafe5569b4313aace312e190 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Mon, 18 Feb 2019 07:25:08 -1000 Subject: [PATCH 074/149] Never overwrite resolved type of symbol --- src/compiler/checker.ts | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 3bd089aff6f..47ed48b5dd0 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -5425,7 +5425,16 @@ namespace ts { function getTypeOfVariableOrParameterOrProperty(symbol: Symbol): Type { const links = getSymbolLinks(symbol); - return links.type || (links.type = getTypeOfVariableOrParameterOrPropertyWorker(symbol)); + if (!links.type) { + const type = getTypeOfVariableOrParameterOrPropertyWorker(symbol); + // For a contextually typed parameter it is possible that a type has already + // been assigned (in assignTypeToParameterAndFixTypeParameters), and we want + // to preserve this type. + if (!links.type) { + links.type = type; + } + } + return links.type; } function getTypeOfVariableOrParameterOrPropertyWorker(symbol: Symbol) { @@ -5469,7 +5478,7 @@ namespace ts { if (symbol.flags & SymbolFlags.ValueModule) { return getTypeOfFuncClassEnumModule(symbol); } - return errorType; + return reportCircularityError(symbol); } let type: Type | undefined; if (isInJSFile(declaration) && @@ -5528,7 +5537,7 @@ namespace ts { if (symbol.flags & SymbolFlags.ValueModule) { return getTypeOfFuncClassEnumModule(symbol); } - type = reportCircularityError(symbol); + return reportCircularityError(symbol); } return type; } From ecfd40891ff3394834df89594a2fd8a563d51343 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Mon, 18 Feb 2019 07:25:22 -1000 Subject: [PATCH 075/149] Accept new baselines --- .../reference/jsFileClassSelfReferencedProperty.types | 4 ++-- tests/baselines/reference/parserES5ForOfStatement18.types | 2 +- tests/baselines/reference/parserES5ForOfStatement19.types | 2 +- tests/baselines/reference/parserForOfStatement18.types | 2 +- tests/baselines/reference/parserForOfStatement19.types | 2 +- tests/baselines/reference/recur1.types | 2 +- .../recursiveExportAssignmentAndFindAliasedType7.types | 2 +- 7 files changed, 8 insertions(+), 8 deletions(-) diff --git a/tests/baselines/reference/jsFileClassSelfReferencedProperty.types b/tests/baselines/reference/jsFileClassSelfReferencedProperty.types index d5c2fe39c9f..204eee67c97 100644 --- a/tests/baselines/reference/jsFileClassSelfReferencedProperty.types +++ b/tests/baselines/reference/jsFileClassSelfReferencedProperty.types @@ -4,11 +4,11 @@ export class StackOverflowTest { constructor () { this.testStackOverflow = this.testStackOverflow.bind(this) ->this.testStackOverflow = this.testStackOverflow.bind(this) : error +>this.testStackOverflow = this.testStackOverflow.bind(this) : any >this.testStackOverflow : any >this : this >testStackOverflow : any ->this.testStackOverflow.bind(this) : error +>this.testStackOverflow.bind(this) : any >this.testStackOverflow.bind : any >this.testStackOverflow : any >this : this diff --git a/tests/baselines/reference/parserES5ForOfStatement18.types b/tests/baselines/reference/parserES5ForOfStatement18.types index 156ed2c68f3..f9544e39a31 100644 --- a/tests/baselines/reference/parserES5ForOfStatement18.types +++ b/tests/baselines/reference/parserES5ForOfStatement18.types @@ -1,5 +1,5 @@ === tests/cases/conformance/parser/ecmascript5/Statements/parserES5ForOfStatement18.ts === for (var of of of) { } >of : any ->of : error +>of : any diff --git a/tests/baselines/reference/parserES5ForOfStatement19.types b/tests/baselines/reference/parserES5ForOfStatement19.types index cc3a1ed01b1..13abc7ae757 100644 --- a/tests/baselines/reference/parserES5ForOfStatement19.types +++ b/tests/baselines/reference/parserES5ForOfStatement19.types @@ -1,5 +1,5 @@ === tests/cases/conformance/parser/ecmascript5/Statements/parserES5ForOfStatement19.ts === for (var of in of) { } >of : any ->of : error +>of : any diff --git a/tests/baselines/reference/parserForOfStatement18.types b/tests/baselines/reference/parserForOfStatement18.types index 3fe8de5b6c1..8e3b52ac877 100644 --- a/tests/baselines/reference/parserForOfStatement18.types +++ b/tests/baselines/reference/parserForOfStatement18.types @@ -1,5 +1,5 @@ === tests/cases/conformance/parser/ecmascript6/Iterators/parserForOfStatement18.ts === for (var of of of) { } >of : any ->of : error +>of : any diff --git a/tests/baselines/reference/parserForOfStatement19.types b/tests/baselines/reference/parserForOfStatement19.types index 04104a9667c..6fcc5e8f792 100644 --- a/tests/baselines/reference/parserForOfStatement19.types +++ b/tests/baselines/reference/parserForOfStatement19.types @@ -1,5 +1,5 @@ === tests/cases/conformance/parser/ecmascript6/Iterators/parserForOfStatement19.ts === for (var of in of) { } >of : any ->of : error +>of : any diff --git a/tests/baselines/reference/recur1.types b/tests/baselines/reference/recur1.types index d4893d27b86..83b4dbd598b 100644 --- a/tests/baselines/reference/recur1.types +++ b/tests/baselines/reference/recur1.types @@ -15,7 +15,7 @@ salt.pepper = function() {} var cobalt = new cobalt.pitch(); >cobalt : any ->new cobalt.pitch() : error +>new cobalt.pitch() : any >cobalt.pitch : any >cobalt : any >pitch : any diff --git a/tests/baselines/reference/recursiveExportAssignmentAndFindAliasedType7.types b/tests/baselines/reference/recursiveExportAssignmentAndFindAliasedType7.types index 939e7beb79b..a5675737c21 100644 --- a/tests/baselines/reference/recursiveExportAssignmentAndFindAliasedType7.types +++ b/tests/baselines/reference/recursiveExportAssignmentAndFindAliasedType7.types @@ -14,7 +14,7 @@ import self = require("recursiveExportAssignmentAndFindAliasedType7_moduleD"); var selfVar = self; >selfVar : any ->self : error +>self : any export = selfVar; >selfVar : any From 451f65332c40fe93ccd703f075dfb85f46d162dc Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Tue, 19 Feb 2019 07:02:37 -1000 Subject: [PATCH 076/149] Improve contextual typing by generic rest parameter --- src/compiler/checker.ts | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 3bd089aff6f..6711d56fe30 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -10669,9 +10669,9 @@ namespace ts { return !!(mapper).typeParameters; } - function cloneTypeMapper(mapper: TypeMapper): TypeMapper { + function cloneTypeMapper(mapper: TypeMapper, extraFlags: InferenceFlags = 0): TypeMapper { return mapper && isInferenceContext(mapper) ? - createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | InferenceFlags.NoDefault, mapper.compareTypes, mapper.inferences) : + createInferenceContext(mapper.typeParameters, mapper.signature, mapper.flags | extraFlags, mapper.compareTypes, mapper.inferences) : mapper; } @@ -19984,7 +19984,7 @@ namespace ts { // We clone the contextual mapper to avoid disturbing a resolution in progress for an // outer call expression. Effectively we just want a snapshot of whatever has been // inferred for any outer call expression so far. - const instantiatedType = instantiateType(contextualType, cloneTypeMapper(getContextualMapper(node))); + const instantiatedType = instantiateType(contextualType, cloneTypeMapper(getContextualMapper(node), InferenceFlags.NoDefault)); // If the contextual type is a generic function type with a single call signature, we // instantiate the type with its own type parameters and type arguments. This ensures that // the type parameters are not erased to type any during type inference such that they can @@ -21652,6 +21652,17 @@ namespace ts { } } } + const restType = getEffectiveRestType(context); + if (restType && restType.flags & TypeFlags.TypeParameter) { + // The contextual signature has a generic rest parameter. We first instantiate the contextual + // signature (without fixing type parameters) and assign types to contextually typed parameters. + const instantiatedContext = instantiateSignature(context, cloneTypeMapper(mapper)); + assignContextualParameterTypes(signature, instantiatedContext); + // We then infer from a tuple type representing the parameters that correspond to the contextual + // rest parameter. + const restPos = getParameterCount(context) - 1; + inferTypes((mapper).inferences, getRestTypeAtPosition(signature, restPos), restType); + } } function assignContextualParameterTypes(signature: Signature, context: Signature) { From f19191b0811a7ad8245b4603aa98eba507fcbc3f Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Tue, 19 Feb 2019 07:02:50 -1000 Subject: [PATCH 077/149] Add tests --- .../types/rest/restTuplesFromContextualTypes.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/tests/cases/conformance/types/rest/restTuplesFromContextualTypes.ts b/tests/cases/conformance/types/rest/restTuplesFromContextualTypes.ts index d5623a000a2..85421a7697b 100644 --- a/tests/cases/conformance/types/rest/restTuplesFromContextualTypes.ts +++ b/tests/cases/conformance/types/rest/restTuplesFromContextualTypes.ts @@ -59,6 +59,21 @@ function f4(t: T) { f((a, b, ...x) => {}); } +declare function f5(f: (...args: T) => U): (...args: T) => U; + +let g0 = f5(() => "hello"); +let g1 = f5((x, y) => 42); +let g2 = f5((x: number, y) => 42); +let g3 = f5((x: number, y: number) => x + y); +let g4 = f5((...args) => true); + +declare function pipe(f: (...args: A) => B, g: (x: B) => C): (...args: A) => C; + +let g5 = pipe(() => true, b => 42); +let g6 = pipe(x => "hello", s => s.length); +let g7 = pipe((x, y) => 42, x => "" + x); +let g8 = pipe((x: number, y: string) => 42, x => "" + x); + // Repro from #25288 declare var tuple: [number, string]; From d0cb0471897d6d357f162da10e871c00b5633a60 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Tue, 19 Feb 2019 07:04:31 -1000 Subject: [PATCH 078/149] Accept new baselines --- .../restTuplesFromContextualTypes.errors.txt | 15 ++ .../restTuplesFromContextualTypes.js | 41 +++++ .../restTuplesFromContextualTypes.symbols | 146 ++++++++++++++---- .../restTuplesFromContextualTypes.types | 109 +++++++++++++ 4 files changed, 282 insertions(+), 29 deletions(-) diff --git a/tests/baselines/reference/restTuplesFromContextualTypes.errors.txt b/tests/baselines/reference/restTuplesFromContextualTypes.errors.txt index 2b94b57f462..5f2c299735b 100644 --- a/tests/baselines/reference/restTuplesFromContextualTypes.errors.txt +++ b/tests/baselines/reference/restTuplesFromContextualTypes.errors.txt @@ -68,6 +68,21 @@ tests/cases/conformance/types/rest/restTuplesFromContextualTypes.ts(56,7): error !!! error TS2345: Property '0' is missing in type 'any[]' but required in type '[T[0], ...T[number][]]'. } + declare function f5(f: (...args: T) => U): (...args: T) => U; + + let g0 = f5(() => "hello"); + let g1 = f5((x, y) => 42); + let g2 = f5((x: number, y) => 42); + let g3 = f5((x: number, y: number) => x + y); + let g4 = f5((...args) => true); + + declare function pipe(f: (...args: A) => B, g: (x: B) => C): (...args: A) => C; + + let g5 = pipe(() => true, b => 42); + let g6 = pipe(x => "hello", s => s.length); + let g7 = pipe((x, y) => 42, x => "" + x); + let g8 = pipe((x: number, y: string) => 42, x => "" + x); + // Repro from #25288 declare var tuple: [number, string]; diff --git a/tests/baselines/reference/restTuplesFromContextualTypes.js b/tests/baselines/reference/restTuplesFromContextualTypes.js index 34e75fcea6e..affe55603bf 100644 --- a/tests/baselines/reference/restTuplesFromContextualTypes.js +++ b/tests/baselines/reference/restTuplesFromContextualTypes.js @@ -57,6 +57,21 @@ function f4(t: T) { f((a, b, ...x) => {}); } +declare function f5(f: (...args: T) => U): (...args: T) => U; + +let g0 = f5(() => "hello"); +let g1 = f5((x, y) => 42); +let g2 = f5((x: number, y) => 42); +let g3 = f5((x: number, y: number) => x + y); +let g4 = f5((...args) => true); + +declare function pipe(f: (...args: A) => B, g: (x: B) => C): (...args: A) => C; + +let g5 = pipe(() => true, b => 42); +let g6 = pipe(x => "hello", s => s.length); +let g7 = pipe((x, y) => 42, x => "" + x); +let g8 = pipe((x: number, y: string) => 42, x => "" + x); + // Repro from #25288 declare var tuple: [number, string]; @@ -275,6 +290,21 @@ function f4(t) { } }); } +var g0 = f5(function () { return "hello"; }); +var g1 = f5(function (x, y) { return 42; }); +var g2 = f5(function (x, y) { return 42; }); +var g3 = f5(function (x, y) { return x + y; }); +var g4 = f5(function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return true; +}); +var g5 = pipe(function () { return true; }, function (b) { return 42; }); +var g6 = pipe(function (x) { return "hello"; }, function (s) { return s.length; }); +var g7 = pipe(function (x, y) { return 42; }, function (x) { return "" + x; }); +var g8 = pipe(function (x, y) { return 42; }, function (x) { return "" + x; }); (function foo(a, b) { }.apply(void 0, tuple)); (function foo() { var rest = []; @@ -309,6 +339,17 @@ declare function f2(cb: (...args: typeof t2) => void): void; declare const t3: [boolean, ...string[]]; declare function f3(cb: (x: number, ...args: typeof t3) => void): void; declare function f4(t: T): void; +declare function f5(f: (...args: T) => U): (...args: T) => U; +declare let g0: () => string; +declare let g1: (x: any, y: any) => number; +declare let g2: (x: number, y: any) => number; +declare let g3: (x: number, y: number) => number; +declare let g4: (...args: any[]) => boolean; +declare function pipe(f: (...args: A) => B, g: (x: B) => C): (...args: A) => C; +declare let g5: () => number; +declare let g6: (x: any) => number; +declare let g7: (x: any, y: any) => string; +declare let g8: (x: number, y: string) => string; declare var tuple: [number, string]; declare function take(cb: (a: number, b: string) => void): void; declare type ArgsUnion = [number, string] | [number, Error]; diff --git a/tests/baselines/reference/restTuplesFromContextualTypes.symbols b/tests/baselines/reference/restTuplesFromContextualTypes.symbols index c58e8cabcae..8cde9f48907 100644 --- a/tests/baselines/reference/restTuplesFromContextualTypes.symbols +++ b/tests/baselines/reference/restTuplesFromContextualTypes.symbols @@ -238,67 +238,155 @@ function f4(t: T) { >x : Symbol(x, Decl(restTuplesFromContextualTypes.ts, 55, 12)) } +declare function f5(f: (...args: T) => U): (...args: T) => U; +>f5 : Symbol(f5, Decl(restTuplesFromContextualTypes.ts, 56, 1)) +>T : Symbol(T, Decl(restTuplesFromContextualTypes.ts, 58, 20)) +>U : Symbol(U, Decl(restTuplesFromContextualTypes.ts, 58, 36)) +>f : Symbol(f, Decl(restTuplesFromContextualTypes.ts, 58, 40)) +>args : Symbol(args, Decl(restTuplesFromContextualTypes.ts, 58, 44)) +>T : Symbol(T, Decl(restTuplesFromContextualTypes.ts, 58, 20)) +>U : Symbol(U, Decl(restTuplesFromContextualTypes.ts, 58, 36)) +>args : Symbol(args, Decl(restTuplesFromContextualTypes.ts, 58, 64)) +>T : Symbol(T, Decl(restTuplesFromContextualTypes.ts, 58, 20)) +>U : Symbol(U, Decl(restTuplesFromContextualTypes.ts, 58, 36)) + +let g0 = f5(() => "hello"); +>g0 : Symbol(g0, Decl(restTuplesFromContextualTypes.ts, 60, 3)) +>f5 : Symbol(f5, Decl(restTuplesFromContextualTypes.ts, 56, 1)) + +let g1 = f5((x, y) => 42); +>g1 : Symbol(g1, Decl(restTuplesFromContextualTypes.ts, 61, 3)) +>f5 : Symbol(f5, Decl(restTuplesFromContextualTypes.ts, 56, 1)) +>x : Symbol(x, Decl(restTuplesFromContextualTypes.ts, 61, 13)) +>y : Symbol(y, Decl(restTuplesFromContextualTypes.ts, 61, 15)) + +let g2 = f5((x: number, y) => 42); +>g2 : Symbol(g2, Decl(restTuplesFromContextualTypes.ts, 62, 3)) +>f5 : Symbol(f5, Decl(restTuplesFromContextualTypes.ts, 56, 1)) +>x : Symbol(x, Decl(restTuplesFromContextualTypes.ts, 62, 13)) +>y : Symbol(y, Decl(restTuplesFromContextualTypes.ts, 62, 23)) + +let g3 = f5((x: number, y: number) => x + y); +>g3 : Symbol(g3, Decl(restTuplesFromContextualTypes.ts, 63, 3)) +>f5 : Symbol(f5, Decl(restTuplesFromContextualTypes.ts, 56, 1)) +>x : Symbol(x, Decl(restTuplesFromContextualTypes.ts, 63, 13)) +>y : Symbol(y, Decl(restTuplesFromContextualTypes.ts, 63, 23)) +>x : Symbol(x, Decl(restTuplesFromContextualTypes.ts, 63, 13)) +>y : Symbol(y, Decl(restTuplesFromContextualTypes.ts, 63, 23)) + +let g4 = f5((...args) => true); +>g4 : Symbol(g4, Decl(restTuplesFromContextualTypes.ts, 64, 3)) +>f5 : Symbol(f5, Decl(restTuplesFromContextualTypes.ts, 56, 1)) +>args : Symbol(args, Decl(restTuplesFromContextualTypes.ts, 64, 13)) + +declare function pipe(f: (...args: A) => B, g: (x: B) => C): (...args: A) => C; +>pipe : Symbol(pipe, Decl(restTuplesFromContextualTypes.ts, 64, 31)) +>A : Symbol(A, Decl(restTuplesFromContextualTypes.ts, 66, 22)) +>B : Symbol(B, Decl(restTuplesFromContextualTypes.ts, 66, 38)) +>C : Symbol(C, Decl(restTuplesFromContextualTypes.ts, 66, 41)) +>f : Symbol(f, Decl(restTuplesFromContextualTypes.ts, 66, 45)) +>args : Symbol(args, Decl(restTuplesFromContextualTypes.ts, 66, 49)) +>A : Symbol(A, Decl(restTuplesFromContextualTypes.ts, 66, 22)) +>B : Symbol(B, Decl(restTuplesFromContextualTypes.ts, 66, 38)) +>g : Symbol(g, Decl(restTuplesFromContextualTypes.ts, 66, 66)) +>x : Symbol(x, Decl(restTuplesFromContextualTypes.ts, 66, 71)) +>B : Symbol(B, Decl(restTuplesFromContextualTypes.ts, 66, 38)) +>C : Symbol(C, Decl(restTuplesFromContextualTypes.ts, 66, 41)) +>args : Symbol(args, Decl(restTuplesFromContextualTypes.ts, 66, 85)) +>A : Symbol(A, Decl(restTuplesFromContextualTypes.ts, 66, 22)) +>C : Symbol(C, Decl(restTuplesFromContextualTypes.ts, 66, 41)) + +let g5 = pipe(() => true, b => 42); +>g5 : Symbol(g5, Decl(restTuplesFromContextualTypes.ts, 68, 3)) +>pipe : Symbol(pipe, Decl(restTuplesFromContextualTypes.ts, 64, 31)) +>b : Symbol(b, Decl(restTuplesFromContextualTypes.ts, 68, 25)) + +let g6 = pipe(x => "hello", s => s.length); +>g6 : Symbol(g6, Decl(restTuplesFromContextualTypes.ts, 69, 3)) +>pipe : Symbol(pipe, Decl(restTuplesFromContextualTypes.ts, 64, 31)) +>x : Symbol(x, Decl(restTuplesFromContextualTypes.ts, 69, 14)) +>s : Symbol(s, Decl(restTuplesFromContextualTypes.ts, 69, 27)) +>s.length : Symbol(String.length, Decl(lib.es5.d.ts, --, --)) +>s : Symbol(s, Decl(restTuplesFromContextualTypes.ts, 69, 27)) +>length : Symbol(String.length, Decl(lib.es5.d.ts, --, --)) + +let g7 = pipe((x, y) => 42, x => "" + x); +>g7 : Symbol(g7, Decl(restTuplesFromContextualTypes.ts, 70, 3)) +>pipe : Symbol(pipe, Decl(restTuplesFromContextualTypes.ts, 64, 31)) +>x : Symbol(x, Decl(restTuplesFromContextualTypes.ts, 70, 15)) +>y : Symbol(y, Decl(restTuplesFromContextualTypes.ts, 70, 17)) +>x : Symbol(x, Decl(restTuplesFromContextualTypes.ts, 70, 27)) +>x : Symbol(x, Decl(restTuplesFromContextualTypes.ts, 70, 27)) + +let g8 = pipe((x: number, y: string) => 42, x => "" + x); +>g8 : Symbol(g8, Decl(restTuplesFromContextualTypes.ts, 71, 3)) +>pipe : Symbol(pipe, Decl(restTuplesFromContextualTypes.ts, 64, 31)) +>x : Symbol(x, Decl(restTuplesFromContextualTypes.ts, 71, 15)) +>y : Symbol(y, Decl(restTuplesFromContextualTypes.ts, 71, 25)) +>x : Symbol(x, Decl(restTuplesFromContextualTypes.ts, 71, 43)) +>x : Symbol(x, Decl(restTuplesFromContextualTypes.ts, 71, 43)) + // Repro from #25288 declare var tuple: [number, string]; ->tuple : Symbol(tuple, Decl(restTuplesFromContextualTypes.ts, 60, 11)) +>tuple : Symbol(tuple, Decl(restTuplesFromContextualTypes.ts, 75, 11)) (function foo(a, b){}(...tuple)); ->foo : Symbol(foo, Decl(restTuplesFromContextualTypes.ts, 61, 1)) ->a : Symbol(a, Decl(restTuplesFromContextualTypes.ts, 61, 14)) ->b : Symbol(b, Decl(restTuplesFromContextualTypes.ts, 61, 16)) ->tuple : Symbol(tuple, Decl(restTuplesFromContextualTypes.ts, 60, 11)) +>foo : Symbol(foo, Decl(restTuplesFromContextualTypes.ts, 76, 1)) +>a : Symbol(a, Decl(restTuplesFromContextualTypes.ts, 76, 14)) +>b : Symbol(b, Decl(restTuplesFromContextualTypes.ts, 76, 16)) +>tuple : Symbol(tuple, Decl(restTuplesFromContextualTypes.ts, 75, 11)) // Repro from #25289 declare function take(cb: (a: number, b: string) => void): void; ->take : Symbol(take, Decl(restTuplesFromContextualTypes.ts, 61, 33)) ->cb : Symbol(cb, Decl(restTuplesFromContextualTypes.ts, 65, 22)) ->a : Symbol(a, Decl(restTuplesFromContextualTypes.ts, 65, 27)) ->b : Symbol(b, Decl(restTuplesFromContextualTypes.ts, 65, 37)) +>take : Symbol(take, Decl(restTuplesFromContextualTypes.ts, 76, 33)) +>cb : Symbol(cb, Decl(restTuplesFromContextualTypes.ts, 80, 22)) +>a : Symbol(a, Decl(restTuplesFromContextualTypes.ts, 80, 27)) +>b : Symbol(b, Decl(restTuplesFromContextualTypes.ts, 80, 37)) (function foo(...rest){}(1, '')); ->foo : Symbol(foo, Decl(restTuplesFromContextualTypes.ts, 67, 1)) ->rest : Symbol(rest, Decl(restTuplesFromContextualTypes.ts, 67, 14)) +>foo : Symbol(foo, Decl(restTuplesFromContextualTypes.ts, 82, 1)) +>rest : Symbol(rest, Decl(restTuplesFromContextualTypes.ts, 82, 14)) take(function(...rest){}); ->take : Symbol(take, Decl(restTuplesFromContextualTypes.ts, 61, 33)) ->rest : Symbol(rest, Decl(restTuplesFromContextualTypes.ts, 68, 14)) +>take : Symbol(take, Decl(restTuplesFromContextualTypes.ts, 76, 33)) +>rest : Symbol(rest, Decl(restTuplesFromContextualTypes.ts, 83, 14)) // Repro from #29833 type ArgsUnion = [number, string] | [number, Error]; ->ArgsUnion : Symbol(ArgsUnion, Decl(restTuplesFromContextualTypes.ts, 68, 26)) +>ArgsUnion : Symbol(ArgsUnion, Decl(restTuplesFromContextualTypes.ts, 83, 26)) >Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) type TupleUnionFunc = (...params: ArgsUnion) => number; ->TupleUnionFunc : Symbol(TupleUnionFunc, Decl(restTuplesFromContextualTypes.ts, 72, 52)) ->params : Symbol(params, Decl(restTuplesFromContextualTypes.ts, 73, 23)) ->ArgsUnion : Symbol(ArgsUnion, Decl(restTuplesFromContextualTypes.ts, 68, 26)) +>TupleUnionFunc : Symbol(TupleUnionFunc, Decl(restTuplesFromContextualTypes.ts, 87, 52)) +>params : Symbol(params, Decl(restTuplesFromContextualTypes.ts, 88, 23)) +>ArgsUnion : Symbol(ArgsUnion, Decl(restTuplesFromContextualTypes.ts, 83, 26)) const funcUnionTupleNoRest: TupleUnionFunc = (num, strOrErr) => { ->funcUnionTupleNoRest : Symbol(funcUnionTupleNoRest, Decl(restTuplesFromContextualTypes.ts, 75, 5)) ->TupleUnionFunc : Symbol(TupleUnionFunc, Decl(restTuplesFromContextualTypes.ts, 72, 52)) ->num : Symbol(num, Decl(restTuplesFromContextualTypes.ts, 75, 46)) ->strOrErr : Symbol(strOrErr, Decl(restTuplesFromContextualTypes.ts, 75, 50)) +>funcUnionTupleNoRest : Symbol(funcUnionTupleNoRest, Decl(restTuplesFromContextualTypes.ts, 90, 5)) +>TupleUnionFunc : Symbol(TupleUnionFunc, Decl(restTuplesFromContextualTypes.ts, 87, 52)) +>num : Symbol(num, Decl(restTuplesFromContextualTypes.ts, 90, 46)) +>strOrErr : Symbol(strOrErr, Decl(restTuplesFromContextualTypes.ts, 90, 50)) return num; ->num : Symbol(num, Decl(restTuplesFromContextualTypes.ts, 75, 46)) +>num : Symbol(num, Decl(restTuplesFromContextualTypes.ts, 90, 46)) }; const funcUnionTupleRest: TupleUnionFunc = (...params) => { ->funcUnionTupleRest : Symbol(funcUnionTupleRest, Decl(restTuplesFromContextualTypes.ts, 79, 5)) ->TupleUnionFunc : Symbol(TupleUnionFunc, Decl(restTuplesFromContextualTypes.ts, 72, 52)) ->params : Symbol(params, Decl(restTuplesFromContextualTypes.ts, 79, 44)) +>funcUnionTupleRest : Symbol(funcUnionTupleRest, Decl(restTuplesFromContextualTypes.ts, 94, 5)) +>TupleUnionFunc : Symbol(TupleUnionFunc, Decl(restTuplesFromContextualTypes.ts, 87, 52)) +>params : Symbol(params, Decl(restTuplesFromContextualTypes.ts, 94, 44)) const [num, strOrErr] = params; ->num : Symbol(num, Decl(restTuplesFromContextualTypes.ts, 80, 9)) ->strOrErr : Symbol(strOrErr, Decl(restTuplesFromContextualTypes.ts, 80, 13)) ->params : Symbol(params, Decl(restTuplesFromContextualTypes.ts, 79, 44)) +>num : Symbol(num, Decl(restTuplesFromContextualTypes.ts, 95, 9)) +>strOrErr : Symbol(strOrErr, Decl(restTuplesFromContextualTypes.ts, 95, 13)) +>params : Symbol(params, Decl(restTuplesFromContextualTypes.ts, 94, 44)) return num; ->num : Symbol(num, Decl(restTuplesFromContextualTypes.ts, 80, 9)) +>num : Symbol(num, Decl(restTuplesFromContextualTypes.ts, 95, 9)) }; diff --git a/tests/baselines/reference/restTuplesFromContextualTypes.types b/tests/baselines/reference/restTuplesFromContextualTypes.types index c282dbbae31..6dd2a6d90cb 100644 --- a/tests/baselines/reference/restTuplesFromContextualTypes.types +++ b/tests/baselines/reference/restTuplesFromContextualTypes.types @@ -351,6 +351,115 @@ function f4(t: T) { >x : T[number][] } +declare function f5(f: (...args: T) => U): (...args: T) => U; +>f5 : (f: (...args: T) => U) => (...args: T) => U +>f : (...args: T) => U +>args : T +>args : T + +let g0 = f5(() => "hello"); +>g0 : () => string +>f5(() => "hello") : () => string +>f5 : (f: (...args: T) => U) => (...args: T) => U +>() => "hello" : () => string +>"hello" : "hello" + +let g1 = f5((x, y) => 42); +>g1 : (x: any, y: any) => number +>f5((x, y) => 42) : (x: any, y: any) => number +>f5 : (f: (...args: T) => U) => (...args: T) => U +>(x, y) => 42 : (x: any, y: any) => number +>x : any +>y : any +>42 : 42 + +let g2 = f5((x: number, y) => 42); +>g2 : (x: number, y: any) => number +>f5((x: number, y) => 42) : (x: number, y: any) => number +>f5 : (f: (...args: T) => U) => (...args: T) => U +>(x: number, y) => 42 : (x: number, y: any) => number +>x : number +>y : any +>42 : 42 + +let g3 = f5((x: number, y: number) => x + y); +>g3 : (x: number, y: number) => number +>f5((x: number, y: number) => x + y) : (x: number, y: number) => number +>f5 : (f: (...args: T) => U) => (...args: T) => U +>(x: number, y: number) => x + y : (x: number, y: number) => number +>x : number +>y : number +>x + y : number +>x : number +>y : number + +let g4 = f5((...args) => true); +>g4 : (...args: any[]) => boolean +>f5((...args) => true) : (...args: any[]) => boolean +>f5 : (f: (...args: T) => U) => (...args: T) => U +>(...args) => true : (...args: any[]) => boolean +>args : any[] +>true : true + +declare function pipe(f: (...args: A) => B, g: (x: B) => C): (...args: A) => C; +>pipe : (f: (...args: A) => B, g: (x: B) => C) => (...args: A) => C +>f : (...args: A) => B +>args : A +>g : (x: B) => C +>x : B +>args : A + +let g5 = pipe(() => true, b => 42); +>g5 : () => number +>pipe(() => true, b => 42) : () => number +>pipe : (f: (...args: A) => B, g: (x: B) => C) => (...args: A) => C +>() => true : () => boolean +>true : true +>b => 42 : (b: boolean) => number +>b : boolean +>42 : 42 + +let g6 = pipe(x => "hello", s => s.length); +>g6 : (x: any) => number +>pipe(x => "hello", s => s.length) : (x: any) => number +>pipe : (f: (...args: A) => B, g: (x: B) => C) => (...args: A) => C +>x => "hello" : (x: any) => string +>x : any +>"hello" : "hello" +>s => s.length : (s: string) => number +>s : string +>s.length : number +>s : string +>length : number + +let g7 = pipe((x, y) => 42, x => "" + x); +>g7 : (x: any, y: any) => string +>pipe((x, y) => 42, x => "" + x) : (x: any, y: any) => string +>pipe : (f: (...args: A) => B, g: (x: B) => C) => (...args: A) => C +>(x, y) => 42 : (x: any, y: any) => number +>x : any +>y : any +>42 : 42 +>x => "" + x : (x: number) => string +>x : number +>"" + x : string +>"" : "" +>x : number + +let g8 = pipe((x: number, y: string) => 42, x => "" + x); +>g8 : (x: number, y: string) => string +>pipe((x: number, y: string) => 42, x => "" + x) : (x: number, y: string) => string +>pipe : (f: (...args: A) => B, g: (x: B) => C) => (...args: A) => C +>(x: number, y: string) => 42 : (x: number, y: string) => number +>x : number +>y : string +>42 : 42 +>x => "" + x : (x: number) => string +>x : number +>"" + x : string +>"" : "" +>x : number + // Repro from #25288 declare var tuple: [number, string]; From 78968b12813e096d6da0ac65df01e6cbccfb1f69 Mon Sep 17 00:00:00 2001 From: Gabriela Araujo Britto Date: Tue, 19 Feb 2019 09:10:27 -0800 Subject: [PATCH 079/149] don't provide refactor in js file --- src/services/refactors/convertToNamedParameters.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/services/refactors/convertToNamedParameters.ts b/src/services/refactors/convertToNamedParameters.ts index 8b966ad0ab2..9c88e5ad337 100644 --- a/src/services/refactors/convertToNamedParameters.ts +++ b/src/services/refactors/convertToNamedParameters.ts @@ -10,6 +10,8 @@ namespace ts.refactor.convertToNamedParameters { function getAvailableActions(context: RefactorContext): ReadonlyArray { const { file, startPosition } = context; + const isJSFile = isSourceFileJS(file); + if (isJSFile) return emptyArray; const functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, context.program.getTypeChecker()); if (!functionDeclaration) return emptyArray; From eafff75c2a334b6bf6f84530c581086e821722fa Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Tue, 19 Feb 2019 11:39:16 -0800 Subject: [PATCH 080/149] Remove diagnostic dependent output in `structuredTypeRelatedTo` (#29817) * Unify variance probing error exceptions between interfaces/aliases * Consistiently return false on variance probe failure * Remove strictFunctionTypes early bail from getVariances so independent type parameters are correctly measured * Fix lint, remove now-redundant change from covariant void check function --- src/compiler/checker.ts | 86 +++--- ...eckInfiniteExpansionTermination.errors.txt | 32 +++ .../complexRecursiveCollections.types | 2 +- .../reference/conditionalTypes1.errors.txt | 8 + .../mappedTypeRelationships.errors.txt | 4 + .../reference/mappedTypes5.errors.txt | 2 + .../recursiveTypeComparison.errors.txt | 27 ++ .../strictFunctionTypesErrors.errors.txt | 82 ++---- ...unionTypeErrorMessageTypeRefs01.errors.txt | 18 +- ...derIndexSignatureRelationsAlign.errors.txt | 82 ++++++ ...ndZeroOrderIndexSignatureRelationsAlign.js | 146 +++++++++++ ...oOrderIndexSignatureRelationsAlign.symbols | 246 ++++++++++++++++++ ...eroOrderIndexSignatureRelationsAlign.types | 168 ++++++++++++ ...erIndexSignatureRelationsAlign2.errors.txt | 79 ++++++ ...dZeroOrderIndexSignatureRelationsAlign2.js | 146 +++++++++++ ...OrderIndexSignatureRelationsAlign2.symbols | 244 +++++++++++++++++ ...roOrderIndexSignatureRelationsAlign2.types | 165 ++++++++++++ ...ndZeroOrderIndexSignatureRelationsAlign.ts | 67 +++++ ...dZeroOrderIndexSignatureRelationsAlign2.ts | 67 +++++ 19 files changed, 1564 insertions(+), 107 deletions(-) create mode 100644 tests/baselines/reference/checkInfiniteExpansionTermination.errors.txt create mode 100644 tests/baselines/reference/recursiveTypeComparison.errors.txt create mode 100644 tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign.errors.txt create mode 100644 tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign.js create mode 100644 tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign.symbols create mode 100644 tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign.types create mode 100644 tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.errors.txt create mode 100644 tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.js create mode 100644 tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.symbols create mode 100644 tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.types create mode 100644 tests/cases/compiler/varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts create mode 100644 tests/cases/compiler/varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 3bd089aff6f..1cce639a781 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -12586,6 +12586,7 @@ namespace ts { let result: Ternary; let originalErrorInfo: DiagnosticMessageChain | undefined; + let varianceCheckFailed = false; const saveErrorInfo = errorInfo; // We limit alias variance probing to only object and conditional types since their alias behavior @@ -12595,11 +12596,10 @@ namespace ts { source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol && !(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) { const variances = getAliasVariances(source.aliasSymbol); - if (result = typeArgumentsRelatedTo(source.aliasTypeArguments, target.aliasTypeArguments, variances, reportErrors)) { - return result; + const varianceResult = relateVariances(source.aliasTypeArguments, target.aliasTypeArguments, variances); + if (varianceResult !== undefined) { + return varianceResult; } - originalErrorInfo = errorInfo; - errorInfo = saveErrorInfo; } if (target.flags & TypeFlags.TypeParameter) { @@ -12764,31 +12764,9 @@ namespace ts { // type references (which are intended by be compared structurally). Obtain the variance // information for the type parameters and relate the type arguments accordingly. const variances = getVariances((source).target); - if (result = typeArgumentsRelatedTo((source).typeArguments, (target).typeArguments, variances, reportErrors)) { - return result; - } - // The type arguments did not relate appropriately, but it may be because we have no variance - // information (in which case typeArgumentsRelatedTo defaulted to covariance for all type - // arguments). It might also be the case that the target type has a 'void' type argument for - // a covariant type parameter that is only used in return positions within the generic type - // (in which case any type argument is permitted on the source side). In those cases we proceed - // with a structural comparison. Otherwise, we know for certain the instantiations aren't - // related and we can return here. - if (variances !== emptyArray && !hasCovariantVoidArgument(target, variances)) { - // In some cases generic types that are covariant in regular type checking mode become - // invariant in --strictFunctionTypes mode because one or more type parameters are used in - // both co- and contravariant positions. In order to make it easier to diagnose *why* such - // types are invariant, if any of the type parameters are invariant we reset the reported - // errors and instead force a structural comparison (which will include elaborations that - // reveal the reason). - if (!(reportErrors && some(variances, v => v === Variance.Invariant))) { - return Ternary.False; - } - // We remember the original error information so we can restore it in case the structural - // comparison unexpectedly succeeds. This can happen when the structural comparison result - // is a Ternary.Maybe for example caused by the recursion depth limiter. - originalErrorInfo = errorInfo; - errorInfo = saveErrorInfo; + const varianceResult = relateVariances((source).typeArguments, (target).typeArguments, variances); + if (varianceResult !== undefined) { + return varianceResult; } } else if (isReadonlyArrayType(target) ? isArrayType(source) || isTupleType(source) : isArrayType(target) && isTupleType(source) && !source.target.readonly) { @@ -12815,16 +12793,48 @@ namespace ts { } } } - if (result) { - if (!originalErrorInfo) { - errorInfo = saveErrorInfo; - return result; - } - errorInfo = originalErrorInfo; + if (varianceCheckFailed && result) { + errorInfo = originalErrorInfo || errorInfo || saveErrorInfo; // Use variance error (there is no structural one) and return false + } + else if (result) { + return result; } } } return Ternary.False; + + function relateVariances(sourceTypeArguments: ReadonlyArray | undefined, targetTypeArguments: ReadonlyArray | undefined, variances: Variance[]) { + if (result = typeArgumentsRelatedTo(sourceTypeArguments, targetTypeArguments, variances, reportErrors)) { + return result; + } + const isCovariantVoid = targetTypeArguments && hasCovariantVoidArgument(targetTypeArguments, variances); + varianceCheckFailed = !isCovariantVoid; + // The type arguments did not relate appropriately, but it may be because we have no variance + // information (in which case typeArgumentsRelatedTo defaulted to covariance for all type + // arguments). It might also be the case that the target type has a 'void' type argument for + // a covariant type parameter that is only used in return positions within the generic type + // (in which case any type argument is permitted on the source side). In those cases we proceed + // with a structural comparison. Otherwise, we know for certain the instantiations aren't + // related and we can return here. + if (variances !== emptyArray && !isCovariantVoid) { + // In some cases generic types that are covariant in regular type checking mode become + // invariant in --strictFunctionTypes mode because one or more type parameters are used in + // both co- and contravariant positions. In order to make it easier to diagnose *why* such + // types are invariant, if any of the type parameters are invariant we reset the reported + // errors and instead force a structural comparison (which will include elaborations that + // reveal the reason). + // We can switch on `reportErrors` here, since varianceCheckFailed guarantees we return `False`, + // we can return `False` early here to skip calculating the structural error message we don't need. + if (varianceCheckFailed && !(reportErrors && some(variances, v => v === Variance.Invariant))) { + return Ternary.False; + } + // We remember the original error information so we can restore it in case the structural + // comparison unexpectedly succeeds. This can happen when the structural comparison result + // is a Ternary.Maybe for example caused by the recursion depth limiter. + originalErrorInfo = errorInfo; + errorInfo = saveErrorInfo; + } + } } // A type [P in S]: X is related to a type [Q in T]: Y if T is related to S and X' is @@ -13333,7 +13343,7 @@ namespace ts { function getVariances(type: GenericType): Variance[] { // Arrays and tuples are known to be covariant, no need to spend time computing this (emptyArray implies covariance for all parameters) - if (!strictFunctionTypes || type === globalArrayType || type === globalReadonlyArrayType || type.objectFlags & ObjectFlags.Tuple) { + if (type === globalArrayType || type === globalReadonlyArrayType || type.objectFlags & ObjectFlags.Tuple) { return emptyArray; } return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference); @@ -13341,9 +13351,9 @@ namespace ts { // Return true if the given type reference has a 'void' type argument for a covariant type parameter. // See comment at call in recursiveTypeRelatedTo for when this case matters. - function hasCovariantVoidArgument(type: TypeReference, variances: Variance[]): boolean { + function hasCovariantVoidArgument(typeArguments: ReadonlyArray, variances: Variance[]): boolean { for (let i = 0; i < variances.length; i++) { - if (variances[i] === Variance.Covariant && type.typeArguments![i].flags & TypeFlags.Void) { + if (variances[i] === Variance.Covariant && typeArguments[i].flags & TypeFlags.Void) { return true; } } diff --git a/tests/baselines/reference/checkInfiniteExpansionTermination.errors.txt b/tests/baselines/reference/checkInfiniteExpansionTermination.errors.txt new file mode 100644 index 00000000000..014087ff627 --- /dev/null +++ b/tests/baselines/reference/checkInfiniteExpansionTermination.errors.txt @@ -0,0 +1,32 @@ +tests/cases/compiler/checkInfiniteExpansionTermination.ts(16,1): error TS2322: Type 'ISubject' is not assignable to type 'IObservable'. + Types of property 'n' are incompatible. + Type 'IObservable' is not assignable to type 'IObservable'. + Type 'Bar[]' is not assignable to type 'Foo[]'. + Property 'x' is missing in type 'Bar' but required in type 'Foo'. + + +==== tests/cases/compiler/checkInfiniteExpansionTermination.ts (1 errors) ==== + // Regression test for #1002 + // Before fix this code would cause infinite loop + + interface IObservable { + n: IObservable; // Needed, must be T[] + } + + // Needed + interface ISubject extends IObservable { } + + interface Foo { x } + interface Bar { y } + + var values: IObservable; + var values2: ISubject; + values = values2; + ~~~~~~ +!!! error TS2322: Type 'ISubject' is not assignable to type 'IObservable'. +!!! error TS2322: Types of property 'n' are incompatible. +!!! error TS2322: Type 'IObservable' is not assignable to type 'IObservable'. +!!! error TS2322: Type 'Bar[]' is not assignable to type 'Foo[]'. +!!! error TS2322: Property 'x' is missing in type 'Bar' but required in type 'Foo'. +!!! related TS2728 tests/cases/compiler/checkInfiniteExpansionTermination.ts:11:17: 'x' is declared here. + \ No newline at end of file diff --git a/tests/baselines/reference/complexRecursiveCollections.types b/tests/baselines/reference/complexRecursiveCollections.types index a9fc13e7d1d..feaff620486 100644 --- a/tests/baselines/reference/complexRecursiveCollections.types +++ b/tests/baselines/reference/complexRecursiveCollections.types @@ -1137,7 +1137,7 @@ declare module Immutable { >Seq : typeof Seq function isSeq(maybeSeq: any): maybeSeq is Seq.Indexed | Seq.Keyed; ->isSeq : (maybeSeq: any) => maybeSeq is Keyed | Indexed +>isSeq : (maybeSeq: any) => maybeSeq is Indexed | Keyed >maybeSeq : any >Seq : any >Seq : any diff --git a/tests/baselines/reference/conditionalTypes1.errors.txt b/tests/baselines/reference/conditionalTypes1.errors.txt index 62239eca7b8..ec35f891615 100644 --- a/tests/baselines/reference/conditionalTypes1.errors.txt +++ b/tests/baselines/reference/conditionalTypes1.errors.txt @@ -17,8 +17,12 @@ tests/cases/conformance/types/conditional/conditionalTypes1.ts(103,5): error TS2 tests/cases/conformance/types/conditional/conditionalTypes1.ts(104,5): error TS2322: Type 'Pick' is not assignable to type 'T'. tests/cases/conformance/types/conditional/conditionalTypes1.ts(106,5): error TS2322: Type 'Pick' is not assignable to type 'Pick'. Type 'T[keyof T] extends Function ? keyof T : never' is not assignable to type 'T[keyof T] extends Function ? never : keyof T'. + Type 'keyof T' is not assignable to type 'never'. + Type 'string | number | symbol' is not assignable to type 'never'. + Type 'string' is not assignable to type 'never'. tests/cases/conformance/types/conditional/conditionalTypes1.ts(108,5): error TS2322: Type 'Pick' is not assignable to type 'Pick'. Type 'T[keyof T] extends Function ? never : keyof T' is not assignable to type 'T[keyof T] extends Function ? keyof T : never'. + Type 'keyof T' is not assignable to type 'never'. tests/cases/conformance/types/conditional/conditionalTypes1.ts(114,5): error TS2322: Type 'keyof T' is not assignable to type 'T[keyof T] extends Function ? keyof T : never'. Type 'string | number | symbol' is not assignable to type 'T[keyof T] extends Function ? keyof T : never'. Type 'string' is not assignable to type 'T[keyof T] extends Function ? keyof T : never'. @@ -183,11 +187,15 @@ tests/cases/conformance/types/conditional/conditionalTypes1.ts(288,43): error TS ~ !!! error TS2322: Type 'Pick' is not assignable to type 'Pick'. !!! error TS2322: Type 'T[keyof T] extends Function ? keyof T : never' is not assignable to type 'T[keyof T] extends Function ? never : keyof T'. +!!! error TS2322: Type 'keyof T' is not assignable to type 'never'. +!!! error TS2322: Type 'string | number | symbol' is not assignable to type 'never'. +!!! error TS2322: Type 'string' is not assignable to type 'never'. z = x; z = y; // Error ~ !!! error TS2322: Type 'Pick' is not assignable to type 'Pick'. !!! error TS2322: Type 'T[keyof T] extends Function ? never : keyof T' is not assignable to type 'T[keyof T] extends Function ? keyof T : never'. +!!! error TS2322: Type 'keyof T' is not assignable to type 'never'. } function f8(x: keyof T, y: FunctionPropertyNames, z: NonFunctionPropertyNames) { diff --git a/tests/baselines/reference/mappedTypeRelationships.errors.txt b/tests/baselines/reference/mappedTypeRelationships.errors.txt index 60a06e000c2..3d637654079 100644 --- a/tests/baselines/reference/mappedTypeRelationships.errors.txt +++ b/tests/baselines/reference/mappedTypeRelationships.errors.txt @@ -34,7 +34,9 @@ tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(66,5): error TS2 tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(66,5): error TS2542: Index signature in type 'Readonly' only permits reading. tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(72,5): error TS2322: Type 'Partial' is not assignable to type 'T'. tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(78,5): error TS2322: Type 'Partial' is not assignable to type 'Partial'. + Type 'Thing' is not assignable to type 'T'. tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(88,5): error TS2322: Type 'Readonly' is not assignable to type 'Readonly'. + Type 'Thing' is not assignable to type 'T'. tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(127,5): error TS2322: Type 'Partial' is not assignable to type 'Identity'. tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(143,5): error TS2322: Type '{ [P in keyof T]: T[P]; }' is not assignable to type '{ [P in keyof T]: U[P]; }'. Type 'T[P]' is not assignable to type 'U[P]'. @@ -197,6 +199,7 @@ tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(168,5): error TS y = x; // Error ~ !!! error TS2322: Type 'Partial' is not assignable to type 'Partial'. +!!! error TS2322: Type 'Thing' is not assignable to type 'T'. } function f40(x: T, y: Readonly) { @@ -209,6 +212,7 @@ tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(168,5): error TS y = x; // Error ~ !!! error TS2322: Type 'Readonly' is not assignable to type 'Readonly'. +!!! error TS2322: Type 'Thing' is not assignable to type 'T'. } type Item = { diff --git a/tests/baselines/reference/mappedTypes5.errors.txt b/tests/baselines/reference/mappedTypes5.errors.txt index d0c32cd1dd9..21d6f98964a 100644 --- a/tests/baselines/reference/mappedTypes5.errors.txt +++ b/tests/baselines/reference/mappedTypes5.errors.txt @@ -1,6 +1,7 @@ tests/cases/conformance/types/mapped/mappedTypes5.ts(6,9): error TS2322: Type 'Partial' is not assignable to type 'Readonly'. tests/cases/conformance/types/mapped/mappedTypes5.ts(8,9): error TS2322: Type 'Partial>' is not assignable to type 'Readonly'. tests/cases/conformance/types/mapped/mappedTypes5.ts(9,9): error TS2322: Type 'Readonly>' is not assignable to type 'Readonly'. + Type 'Partial' is not assignable to type 'T'. ==== tests/cases/conformance/types/mapped/mappedTypes5.ts (3 errors) ==== @@ -19,6 +20,7 @@ tests/cases/conformance/types/mapped/mappedTypes5.ts(9,9): error TS2322: Type 'R let b4: Readonly = rp; // Error ~~ !!! error TS2322: Type 'Readonly>' is not assignable to type 'Readonly'. +!!! error TS2322: Type 'Partial' is not assignable to type 'T'. let c1: Partial> = p; let c2: Partial> = r; let c3: Partial> = pr; diff --git a/tests/baselines/reference/recursiveTypeComparison.errors.txt b/tests/baselines/reference/recursiveTypeComparison.errors.txt new file mode 100644 index 00000000000..f647763b2e2 --- /dev/null +++ b/tests/baselines/reference/recursiveTypeComparison.errors.txt @@ -0,0 +1,27 @@ +tests/cases/compiler/recursiveTypeComparison.ts(14,5): error TS2322: Type 'Observable<{}>' is not assignable to type 'Property'. + Types of property 'needThisOne' are incompatible. + Type 'Observable<{}>' is not assignable to type 'Observable'. + Type '{}' is not assignable to type 'number'. + + +==== tests/cases/compiler/recursiveTypeComparison.ts (1 errors) ==== + // Before fix this would take an exceeding long time to complete (#1170) + + interface Observable { + // This member can't be of type T, Property, or Observable + needThisOne: Observable; + // Add more to make it slower + expo1: Property; // 0.31 seconds in check + expo2: Property; // 3.11 seconds + expo3: Property; // 82.28 seconds + } + interface Property extends Observable { } + + var p: Observable<{}>; + var stuck: Property = p; + ~~~~~ +!!! error TS2322: Type 'Observable<{}>' is not assignable to type 'Property'. +!!! error TS2322: Types of property 'needThisOne' are incompatible. +!!! error TS2322: Type 'Observable<{}>' is not assignable to type 'Observable'. +!!! error TS2322: Type '{}' is not assignable to type 'number'. + \ No newline at end of file diff --git a/tests/baselines/reference/strictFunctionTypesErrors.errors.txt b/tests/baselines/reference/strictFunctionTypesErrors.errors.txt index 369919850f0..3ff04c44fb7 100644 --- a/tests/baselines/reference/strictFunctionTypesErrors.errors.txt +++ b/tests/baselines/reference/strictFunctionTypesErrors.errors.txt @@ -17,19 +17,15 @@ tests/cases/compiler/strictFunctionTypesErrors.ts(21,1): error TS2322: Type '(x: tests/cases/compiler/strictFunctionTypesErrors.ts(23,1): error TS2322: Type '(x: string) => Object' is not assignable to type '(x: string) => string'. Type 'Object' is not assignable to type 'string'. tests/cases/compiler/strictFunctionTypesErrors.ts(33,1): error TS2322: Type 'Func' is not assignable to type 'Func'. - Types of parameters 'x' and 'x' are incompatible. - Type 'Object' is not assignable to type 'string'. + Type 'Object' is not assignable to type 'string'. tests/cases/compiler/strictFunctionTypesErrors.ts(34,1): error TS2322: Type 'Func' is not assignable to type 'Func'. - Types of parameters 'x' and 'x' are incompatible. - Type 'Object' is not assignable to type 'string'. + Type 'Object' is not assignable to type 'string'. tests/cases/compiler/strictFunctionTypesErrors.ts(36,1): error TS2322: Type 'Func' is not assignable to type 'Func'. Type 'Object' is not assignable to type 'string'. tests/cases/compiler/strictFunctionTypesErrors.ts(37,1): error TS2322: Type 'Func' is not assignable to type 'Func'. - Types of parameters 'x' and 'x' are incompatible. - Type 'Object' is not assignable to type 'string'. + Type 'Object' is not assignable to type 'string'. tests/cases/compiler/strictFunctionTypesErrors.ts(38,1): error TS2322: Type 'Func' is not assignable to type 'Func'. - Types of parameters 'x' and 'x' are incompatible. - Type 'Object' is not assignable to type 'string'. + Type 'Object' is not assignable to type 'string'. tests/cases/compiler/strictFunctionTypesErrors.ts(44,1): error TS2322: Type 'Func' is not assignable to type 'Func'. Type 'Object' is not assignable to type 'string'. tests/cases/compiler/strictFunctionTypesErrors.ts(46,1): error TS2322: Type 'Func' is not assignable to type 'Func'. @@ -39,37 +35,26 @@ tests/cases/compiler/strictFunctionTypesErrors.ts(57,1): error TS2322: Type 'Fun tests/cases/compiler/strictFunctionTypesErrors.ts(58,1): error TS2322: Type 'Func, Object>' is not assignable to type 'Func, string>'. Type 'Object' is not assignable to type 'string'. tests/cases/compiler/strictFunctionTypesErrors.ts(61,1): error TS2322: Type 'Func, Object>' is not assignable to type 'Func, Object>'. - Types of parameters 'x' and 'x' are incompatible. - Types of parameters 'x' and 'x' are incompatible. - Type 'Object' is not assignable to type 'string'. + Type 'Func' is not assignable to type 'Func'. + Type 'Object' is not assignable to type 'string'. tests/cases/compiler/strictFunctionTypesErrors.ts(62,1): error TS2322: Type 'Func, string>' is not assignable to type 'Func, Object>'. - Types of parameters 'x' and 'x' are incompatible. - Types of parameters 'x' and 'x' are incompatible. - Type 'Object' is not assignable to type 'string'. + Type 'Func' is not assignable to type 'Func'. tests/cases/compiler/strictFunctionTypesErrors.ts(65,1): error TS2322: Type 'Func, Object>' is not assignable to type 'Func, string>'. - Types of parameters 'x' and 'x' are incompatible. - Types of parameters 'x' and 'x' are incompatible. - Type 'Object' is not assignable to type 'string'. + Type 'Func' is not assignable to type 'Func'. tests/cases/compiler/strictFunctionTypesErrors.ts(66,1): error TS2322: Type 'Func, string>' is not assignable to type 'Func, string>'. - Types of parameters 'x' and 'x' are incompatible. - Types of parameters 'x' and 'x' are incompatible. - Type 'Object' is not assignable to type 'string'. + Type 'Func' is not assignable to type 'Func'. tests/cases/compiler/strictFunctionTypesErrors.ts(67,1): error TS2322: Type 'Func, Object>' is not assignable to type 'Func, string>'. Type 'Object' is not assignable to type 'string'. tests/cases/compiler/strictFunctionTypesErrors.ts(74,1): error TS2322: Type 'Func>' is not assignable to type 'Func>'. Type 'Func' is not assignable to type 'Func'. tests/cases/compiler/strictFunctionTypesErrors.ts(75,1): error TS2322: Type 'Func>' is not assignable to type 'Func>'. - Types of parameters 'x' and 'x' are incompatible. - Type 'Object' is not assignable to type 'string'. + Type 'Object' is not assignable to type 'string'. tests/cases/compiler/strictFunctionTypesErrors.ts(76,1): error TS2322: Type 'Func>' is not assignable to type 'Func>'. - Types of parameters 'x' and 'x' are incompatible. - Type 'Object' is not assignable to type 'string'. + Type 'Object' is not assignable to type 'string'. tests/cases/compiler/strictFunctionTypesErrors.ts(79,1): error TS2322: Type 'Func>' is not assignable to type 'Func>'. - Types of parameters 'x' and 'x' are incompatible. - Type 'Object' is not assignable to type 'string'. + Type 'Object' is not assignable to type 'string'. tests/cases/compiler/strictFunctionTypesErrors.ts(80,1): error TS2322: Type 'Func>' is not assignable to type 'Func>'. - Types of parameters 'x' and 'x' are incompatible. - Type 'Object' is not assignable to type 'string'. + Type 'Object' is not assignable to type 'string'. tests/cases/compiler/strictFunctionTypesErrors.ts(83,1): error TS2322: Type 'Func>' is not assignable to type 'Func>'. Type 'Func' is not assignable to type 'Func'. tests/cases/compiler/strictFunctionTypesErrors.ts(84,1): error TS2322: Type 'Func>' is not assignable to type 'Func>'. @@ -162,13 +147,11 @@ tests/cases/compiler/strictFunctionTypesErrors.ts(155,5): error TS2322: Type '(c g1 = g3; // Error ~~ !!! error TS2322: Type 'Func' is not assignable to type 'Func'. -!!! error TS2322: Types of parameters 'x' and 'x' are incompatible. -!!! error TS2322: Type 'Object' is not assignable to type 'string'. +!!! error TS2322: Type 'Object' is not assignable to type 'string'. g1 = g4; // Error ~~ !!! error TS2322: Type 'Func' is not assignable to type 'Func'. -!!! error TS2322: Types of parameters 'x' and 'x' are incompatible. -!!! error TS2322: Type 'Object' is not assignable to type 'string'. +!!! error TS2322: Type 'Object' is not assignable to type 'string'. g2 = g1; // Error ~~ @@ -177,13 +160,11 @@ tests/cases/compiler/strictFunctionTypesErrors.ts(155,5): error TS2322: Type '(c g2 = g3; // Error ~~ !!! error TS2322: Type 'Func' is not assignable to type 'Func'. -!!! error TS2322: Types of parameters 'x' and 'x' are incompatible. -!!! error TS2322: Type 'Object' is not assignable to type 'string'. +!!! error TS2322: Type 'Object' is not assignable to type 'string'. g2 = g4; // Error ~~ !!! error TS2322: Type 'Func' is not assignable to type 'Func'. -!!! error TS2322: Types of parameters 'x' and 'x' are incompatible. -!!! error TS2322: Type 'Object' is not assignable to type 'string'. +!!! error TS2322: Type 'Object' is not assignable to type 'string'. g3 = g1; // Ok g3 = g2; // Ok @@ -221,29 +202,22 @@ tests/cases/compiler/strictFunctionTypesErrors.ts(155,5): error TS2322: Type '(c h3 = h1; // Error ~~ !!! error TS2322: Type 'Func, Object>' is not assignable to type 'Func, Object>'. -!!! error TS2322: Types of parameters 'x' and 'x' are incompatible. -!!! error TS2322: Types of parameters 'x' and 'x' are incompatible. -!!! error TS2322: Type 'Object' is not assignable to type 'string'. +!!! error TS2322: Type 'Func' is not assignable to type 'Func'. +!!! error TS2322: Type 'Object' is not assignable to type 'string'. h3 = h2; // Error ~~ !!! error TS2322: Type 'Func, string>' is not assignable to type 'Func, Object>'. -!!! error TS2322: Types of parameters 'x' and 'x' are incompatible. -!!! error TS2322: Types of parameters 'x' and 'x' are incompatible. -!!! error TS2322: Type 'Object' is not assignable to type 'string'. +!!! error TS2322: Type 'Func' is not assignable to type 'Func'. h3 = h4; // Ok h4 = h1; // Error ~~ !!! error TS2322: Type 'Func, Object>' is not assignable to type 'Func, string>'. -!!! error TS2322: Types of parameters 'x' and 'x' are incompatible. -!!! error TS2322: Types of parameters 'x' and 'x' are incompatible. -!!! error TS2322: Type 'Object' is not assignable to type 'string'. +!!! error TS2322: Type 'Func' is not assignable to type 'Func'. h4 = h2; // Error ~~ !!! error TS2322: Type 'Func, string>' is not assignable to type 'Func, string>'. -!!! error TS2322: Types of parameters 'x' and 'x' are incompatible. -!!! error TS2322: Types of parameters 'x' and 'x' are incompatible. -!!! error TS2322: Type 'Object' is not assignable to type 'string'. +!!! error TS2322: Type 'Func' is not assignable to type 'Func'. h4 = h3; // Error ~~ !!! error TS2322: Type 'Func, Object>' is not assignable to type 'Func, string>'. @@ -261,25 +235,21 @@ tests/cases/compiler/strictFunctionTypesErrors.ts(155,5): error TS2322: Type '(c i1 = i3; // Error ~~ !!! error TS2322: Type 'Func>' is not assignable to type 'Func>'. -!!! error TS2322: Types of parameters 'x' and 'x' are incompatible. -!!! error TS2322: Type 'Object' is not assignable to type 'string'. +!!! error TS2322: Type 'Object' is not assignable to type 'string'. i1 = i4; // Error ~~ !!! error TS2322: Type 'Func>' is not assignable to type 'Func>'. -!!! error TS2322: Types of parameters 'x' and 'x' are incompatible. -!!! error TS2322: Type 'Object' is not assignable to type 'string'. +!!! error TS2322: Type 'Object' is not assignable to type 'string'. i2 = i1; // Ok i2 = i3; // Error ~~ !!! error TS2322: Type 'Func>' is not assignable to type 'Func>'. -!!! error TS2322: Types of parameters 'x' and 'x' are incompatible. -!!! error TS2322: Type 'Object' is not assignable to type 'string'. +!!! error TS2322: Type 'Object' is not assignable to type 'string'. i2 = i4; // Error ~~ !!! error TS2322: Type 'Func>' is not assignable to type 'Func>'. -!!! error TS2322: Types of parameters 'x' and 'x' are incompatible. -!!! error TS2322: Type 'Object' is not assignable to type 'string'. +!!! error TS2322: Type 'Object' is not assignable to type 'string'. i3 = i1; // Ok i3 = i2; // Error diff --git a/tests/baselines/reference/unionTypeErrorMessageTypeRefs01.errors.txt b/tests/baselines/reference/unionTypeErrorMessageTypeRefs01.errors.txt index 5fdeab58610..ab661b6fee7 100644 --- a/tests/baselines/reference/unionTypeErrorMessageTypeRefs01.errors.txt +++ b/tests/baselines/reference/unionTypeErrorMessageTypeRefs01.errors.txt @@ -9,16 +9,13 @@ tests/cases/compiler/unionTypeErrorMessageTypeRefs01.ts(27,1): error TS2322: Typ Property 'kwah' is missing in type 'Foo' but required in type 'Kwah'. tests/cases/compiler/unionTypeErrorMessageTypeRefs01.ts(48,1): error TS2322: Type 'X' is not assignable to type 'X | Y | Z'. Type 'X' is not assignable to type 'X'. - Types of property 'xProp' are incompatible. - Type 'Foo' is not assignable to type 'Bar'. + Type 'Foo' is not assignable to type 'Bar'. tests/cases/compiler/unionTypeErrorMessageTypeRefs01.ts(49,1): error TS2322: Type 'Y' is not assignable to type 'X | Y | Z'. Type 'Y' is not assignable to type 'Y'. - Types of property 'yProp' are incompatible. - Type 'Foo' is not assignable to type 'Baz'. + Type 'Foo' is not assignable to type 'Baz'. tests/cases/compiler/unionTypeErrorMessageTypeRefs01.ts(50,1): error TS2322: Type 'Z' is not assignable to type 'X | Y | Z'. Type 'Z' is not assignable to type 'Z'. - Types of property 'zProp' are incompatible. - Type 'Foo' is not assignable to type 'Kwah'. + Type 'Foo' is not assignable to type 'Kwah'. ==== tests/cases/compiler/unionTypeErrorMessageTypeRefs01.ts (6 errors) ==== @@ -88,17 +85,14 @@ tests/cases/compiler/unionTypeErrorMessageTypeRefs01.ts(50,1): error TS2322: Typ ~~~~~~~~~~~~~~~~~~ !!! error TS2322: Type 'X' is not assignable to type 'X | Y | Z'. !!! error TS2322: Type 'X' is not assignable to type 'X'. -!!! error TS2322: Types of property 'xProp' are incompatible. -!!! error TS2322: Type 'Foo' is not assignable to type 'Bar'. +!!! error TS2322: Type 'Foo' is not assignable to type 'Bar'. thingOfTypeAliases = y; ~~~~~~~~~~~~~~~~~~ !!! error TS2322: Type 'Y' is not assignable to type 'X | Y | Z'. !!! error TS2322: Type 'Y' is not assignable to type 'Y'. -!!! error TS2322: Types of property 'yProp' are incompatible. -!!! error TS2322: Type 'Foo' is not assignable to type 'Baz'. +!!! error TS2322: Type 'Foo' is not assignable to type 'Baz'. thingOfTypeAliases = z; ~~~~~~~~~~~~~~~~~~ !!! error TS2322: Type 'Z' is not assignable to type 'X | Y | Z'. !!! error TS2322: Type 'Z' is not assignable to type 'Z'. -!!! error TS2322: Types of property 'zProp' are incompatible. -!!! error TS2322: Type 'Foo' is not assignable to type 'Kwah'. \ No newline at end of file +!!! error TS2322: Type 'Foo' is not assignable to type 'Kwah'. \ No newline at end of file diff --git a/tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign.errors.txt b/tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign.errors.txt new file mode 100644 index 00000000000..47f97958f0d --- /dev/null +++ b/tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign.errors.txt @@ -0,0 +1,82 @@ +tests/cases/compiler/varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts(63,6): error TS2345: Argument of type 'NeededInfo>' is not assignable to parameter of type 'NeededInfo<{}>'. + Types of property 'ASchema' are incompatible. + Type 'ToA>' is not assignable to type 'ToA<{}>'. + Type '{}' is not assignable to type 'ToB<{ initialize: any; }>'. +tests/cases/compiler/varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts(66,38): error TS2344: Type 'NeededInfo>' does not satisfy the constraint 'NeededInfo<{}>'. + + +==== tests/cases/compiler/varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts (2 errors) ==== + type Either = Left | Right; + + class Left { + readonly _tag: 'Left' = 'Left' + readonly _A!: A + readonly _L!: L + constructor(readonly value: L) {} + /** The given function is applied if this is a `Right` */ + map(f: (a: A) => B): Either { + return this as any + } + ap(fab: Either B>): Either { + return null as any + } + } + + class Right { + readonly _tag: 'Right' = 'Right' + readonly _A!: A + readonly _L!: L + constructor(readonly value: A) {} + map(f: (a: A) => B): Either { + return new Right(f(this.value)) + } + ap(fab: Either B>): Either { + return null as any; + } + } + + class Type { + readonly _A!: A; + readonly _O!: O; + readonly _I!: I; + constructor( + /** a unique name for this codec */ + readonly name: string, + /** a custom type guard */ + readonly is: (u: unknown) => u is A, + /** succeeds if a value of type I can be decoded to a value of type A */ + readonly validate: (input: I, context: {}[]) => Either<{}[], A>, + /** converts a value of type A to a value of type O */ + readonly encode: (a: A) => O + ) {} + /** a version of `validate` with a default context */ + decode(i: I): Either<{}[], A> { return null as any; } + } + + interface Any extends Type {} + + type TypeOf = C["_A"]; + + type ToB = { [k in keyof S]: TypeOf }; + type ToA = { [k in keyof S]: Type }; + + type NeededInfo = { + ASchema: ToA; + }; + + export type MyInfo = NeededInfo>; + + const tmp1: MyInfo = null!; + function tmp2(n: N) {} + tmp2(tmp1); // uncommenting this line removes a type error from a completely unrelated line ?? + ~~~~ +!!! error TS2345: Argument of type 'NeededInfo>' is not assignable to parameter of type 'NeededInfo<{}>'. +!!! error TS2345: Types of property 'ASchema' are incompatible. +!!! error TS2345: Type 'ToA>' is not assignable to type 'ToA<{}>'. +!!! error TS2345: Type '{}' is not assignable to type 'ToB<{ initialize: any; }>'. +!!! related TS2728 tests/cases/compiler/varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts:59:39: 'initialize' is declared here. + + class Server {} + export class MyServer extends Server {} // not assignable error at `MyInfo` + ~~~~~~ +!!! error TS2344: Type 'NeededInfo>' does not satisfy the constraint 'NeededInfo<{}>'. \ No newline at end of file diff --git a/tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign.js b/tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign.js new file mode 100644 index 00000000000..cbac03d7a82 --- /dev/null +++ b/tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign.js @@ -0,0 +1,146 @@ +//// [varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts] +type Either = Left | Right; + +class Left { + readonly _tag: 'Left' = 'Left' + readonly _A!: A + readonly _L!: L + constructor(readonly value: L) {} + /** The given function is applied if this is a `Right` */ + map(f: (a: A) => B): Either { + return this as any + } + ap(fab: Either B>): Either { + return null as any + } +} + +class Right { + readonly _tag: 'Right' = 'Right' + readonly _A!: A + readonly _L!: L + constructor(readonly value: A) {} + map(f: (a: A) => B): Either { + return new Right(f(this.value)) + } + ap(fab: Either B>): Either { + return null as any; + } +} + +class Type { + readonly _A!: A; + readonly _O!: O; + readonly _I!: I; + constructor( + /** a unique name for this codec */ + readonly name: string, + /** a custom type guard */ + readonly is: (u: unknown) => u is A, + /** succeeds if a value of type I can be decoded to a value of type A */ + readonly validate: (input: I, context: {}[]) => Either<{}[], A>, + /** converts a value of type A to a value of type O */ + readonly encode: (a: A) => O + ) {} + /** a version of `validate` with a default context */ + decode(i: I): Either<{}[], A> { return null as any; } +} + +interface Any extends Type {} + +type TypeOf = C["_A"]; + +type ToB = { [k in keyof S]: TypeOf }; +type ToA = { [k in keyof S]: Type }; + +type NeededInfo = { + ASchema: ToA; +}; + +export type MyInfo = NeededInfo>; + +const tmp1: MyInfo = null!; +function tmp2(n: N) {} +tmp2(tmp1); // uncommenting this line removes a type error from a completely unrelated line ?? + +class Server {} +export class MyServer extends Server {} // not assignable error at `MyInfo` + +//// [varianceProblingAndZeroOrderIndexSignatureRelationsAlign.js] +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +exports.__esModule = true; +var Left = /** @class */ (function () { + function Left(value) { + this.value = value; + this._tag = 'Left'; + } + /** The given function is applied if this is a `Right` */ + Left.prototype.map = function (f) { + return this; + }; + Left.prototype.ap = function (fab) { + return null; + }; + return Left; +}()); +var Right = /** @class */ (function () { + function Right(value) { + this.value = value; + this._tag = 'Right'; + } + Right.prototype.map = function (f) { + return new Right(f(this.value)); + }; + Right.prototype.ap = function (fab) { + return null; + }; + return Right; +}()); +var Type = /** @class */ (function () { + function Type( + /** a unique name for this codec */ + name, + /** a custom type guard */ + is, + /** succeeds if a value of type I can be decoded to a value of type A */ + validate, + /** converts a value of type A to a value of type O */ + encode) { + this.name = name; + this.is = is; + this.validate = validate; + this.encode = encode; + } + /** a version of `validate` with a default context */ + Type.prototype.decode = function (i) { return null; }; + return Type; +}()); +var tmp1 = null; +function tmp2(n) { } +tmp2(tmp1); // uncommenting this line removes a type error from a completely unrelated line ?? +var Server = /** @class */ (function () { + function Server() { + } + return Server; +}()); +var MyServer = /** @class */ (function (_super) { + __extends(MyServer, _super); + function MyServer() { + return _super !== null && _super.apply(this, arguments) || this; + } + return MyServer; +}(Server)); // not assignable error at `MyInfo` +exports.MyServer = MyServer; diff --git a/tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign.symbols b/tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign.symbols new file mode 100644 index 00000000000..bd979284063 --- /dev/null +++ b/tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign.symbols @@ -0,0 +1,246 @@ +=== tests/cases/compiler/varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts === +type Either = Left | Right; +>Either : Symbol(Either, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 0, 0)) +>L : Symbol(L, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 0, 12)) +>A : Symbol(A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 0, 14)) +>Left : Symbol(Left, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 0, 45)) +>L : Symbol(L, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 0, 12)) +>A : Symbol(A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 0, 14)) +>Right : Symbol(Right, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 14, 1)) +>L : Symbol(L, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 0, 12)) +>A : Symbol(A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 0, 14)) + +class Left { +>Left : Symbol(Left, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 0, 45)) +>L : Symbol(L, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 2, 11)) +>A : Symbol(A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 2, 13)) + + readonly _tag: 'Left' = 'Left' +>_tag : Symbol(Left._tag, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 2, 18)) + + readonly _A!: A +>_A : Symbol(Left._A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 3, 34)) +>A : Symbol(A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 2, 13)) + + readonly _L!: L +>_L : Symbol(Left._L, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 4, 19)) +>L : Symbol(L, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 2, 11)) + + constructor(readonly value: L) {} +>value : Symbol(Left.value, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 6, 16)) +>L : Symbol(L, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 2, 11)) + + /** The given function is applied if this is a `Right` */ + map(f: (a: A) => B): Either { +>map : Symbol(Left.map, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 6, 37)) +>B : Symbol(B, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 8, 8)) +>f : Symbol(f, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 8, 11)) +>a : Symbol(a, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 8, 15)) +>A : Symbol(A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 2, 13)) +>B : Symbol(B, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 8, 8)) +>Either : Symbol(Either, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 0, 0)) +>L : Symbol(L, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 2, 11)) +>B : Symbol(B, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 8, 8)) + + return this as any +>this : Symbol(Left, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 0, 45)) + } + ap(fab: Either B>): Either { +>ap : Symbol(Left.ap, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 10, 5)) +>B : Symbol(B, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 11, 7)) +>fab : Symbol(fab, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 11, 10)) +>Either : Symbol(Either, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 0, 0)) +>L : Symbol(L, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 2, 11)) +>a : Symbol(a, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 11, 26)) +>A : Symbol(A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 2, 13)) +>B : Symbol(B, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 11, 7)) +>Either : Symbol(Either, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 0, 0)) +>L : Symbol(L, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 2, 11)) +>B : Symbol(B, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 11, 7)) + + return null as any + } +} + +class Right { +>Right : Symbol(Right, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 14, 1)) +>L : Symbol(L, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 16, 12)) +>A : Symbol(A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 16, 14)) + + readonly _tag: 'Right' = 'Right' +>_tag : Symbol(Right._tag, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 16, 19)) + + readonly _A!: A +>_A : Symbol(Right._A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 17, 36)) +>A : Symbol(A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 16, 14)) + + readonly _L!: L +>_L : Symbol(Right._L, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 18, 19)) +>L : Symbol(L, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 16, 12)) + + constructor(readonly value: A) {} +>value : Symbol(Right.value, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 20, 16)) +>A : Symbol(A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 16, 14)) + + map(f: (a: A) => B): Either { +>map : Symbol(Right.map, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 20, 37)) +>B : Symbol(B, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 21, 8)) +>f : Symbol(f, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 21, 11)) +>a : Symbol(a, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 21, 15)) +>A : Symbol(A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 16, 14)) +>B : Symbol(B, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 21, 8)) +>Either : Symbol(Either, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 0, 0)) +>L : Symbol(L, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 16, 12)) +>B : Symbol(B, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 21, 8)) + + return new Right(f(this.value)) +>Right : Symbol(Right, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 14, 1)) +>f : Symbol(f, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 21, 11)) +>this.value : Symbol(Right.value, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 20, 16)) +>this : Symbol(Right, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 14, 1)) +>value : Symbol(Right.value, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 20, 16)) + } + ap(fab: Either B>): Either { +>ap : Symbol(Right.ap, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 23, 5)) +>B : Symbol(B, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 24, 7)) +>fab : Symbol(fab, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 24, 10)) +>Either : Symbol(Either, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 0, 0)) +>L : Symbol(L, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 16, 12)) +>a : Symbol(a, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 24, 26)) +>A : Symbol(A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 16, 14)) +>B : Symbol(B, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 24, 7)) +>Either : Symbol(Either, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 0, 0)) +>L : Symbol(L, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 16, 12)) +>B : Symbol(B, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 24, 7)) + + return null as any; + } +} + +class Type { +>Type : Symbol(Type, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 27, 1)) +>A : Symbol(A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 29, 11)) +>O : Symbol(O, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 29, 13)) +>A : Symbol(A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 29, 11)) +>I : Symbol(I, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 29, 20)) + + readonly _A!: A; +>_A : Symbol(Type._A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 29, 35)) +>A : Symbol(A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 29, 11)) + + readonly _O!: O; +>_O : Symbol(Type._O, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 30, 18)) +>O : Symbol(O, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 29, 13)) + + readonly _I!: I; +>_I : Symbol(Type._I, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 31, 18)) +>I : Symbol(I, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 29, 20)) + + constructor( + /** a unique name for this codec */ + readonly name: string, +>name : Symbol(Type.name, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 33, 14)) + + /** a custom type guard */ + readonly is: (u: unknown) => u is A, +>is : Symbol(Type.is, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 35, 26)) +>u : Symbol(u, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 37, 18)) +>u : Symbol(u, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 37, 18)) +>A : Symbol(A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 29, 11)) + + /** succeeds if a value of type I can be decoded to a value of type A */ + readonly validate: (input: I, context: {}[]) => Either<{}[], A>, +>validate : Symbol(Type.validate, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 37, 40)) +>input : Symbol(input, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 39, 24)) +>I : Symbol(I, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 29, 20)) +>context : Symbol(context, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 39, 33)) +>Either : Symbol(Either, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 0, 0)) +>A : Symbol(A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 29, 11)) + + /** converts a value of type A to a value of type O */ + readonly encode: (a: A) => O +>encode : Symbol(Type.encode, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 39, 68)) +>a : Symbol(a, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 41, 22)) +>A : Symbol(A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 29, 11)) +>O : Symbol(O, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 29, 13)) + + ) {} + /** a version of `validate` with a default context */ + decode(i: I): Either<{}[], A> { return null as any; } +>decode : Symbol(Type.decode, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 42, 6)) +>i : Symbol(i, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 44, 9)) +>I : Symbol(I, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 29, 20)) +>Either : Symbol(Either, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 0, 0)) +>A : Symbol(A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 29, 11)) +} + +interface Any extends Type {} +>Any : Symbol(Any, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 45, 1)) +>Type : Symbol(Type, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 27, 1)) + +type TypeOf = C["_A"]; +>TypeOf : Symbol(TypeOf, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 47, 44)) +>C : Symbol(C, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 49, 12)) +>Any : Symbol(Any, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 45, 1)) +>C : Symbol(C, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 49, 12)) + +type ToB = { [k in keyof S]: TypeOf }; +>ToB : Symbol(ToB, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 49, 37)) +>S : Symbol(S, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 51, 9)) +>k : Symbol(k, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 51, 29)) +>S : Symbol(S, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 51, 9)) +>TypeOf : Symbol(TypeOf, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 47, 44)) +>S : Symbol(S, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 51, 9)) +>k : Symbol(k, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 51, 29)) + +type ToA = { [k in keyof S]: Type }; +>ToA : Symbol(ToA, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 51, 59)) +>S : Symbol(S, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 52, 9)) +>k : Symbol(k, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 52, 17)) +>S : Symbol(S, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 52, 9)) +>Type : Symbol(Type, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 27, 1)) +>S : Symbol(S, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 52, 9)) +>k : Symbol(k, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 52, 17)) + +type NeededInfo = { +>NeededInfo : Symbol(NeededInfo, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 52, 45)) +>MyNamespaceSchema : Symbol(MyNamespaceSchema, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 54, 16)) + + ASchema: ToA; +>ASchema : Symbol(ASchema, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 54, 43)) +>ToA : Symbol(ToA, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 51, 59)) +>MyNamespaceSchema : Symbol(MyNamespaceSchema, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 54, 16)) + +}; + +export type MyInfo = NeededInfo>; +>MyInfo : Symbol(MyInfo, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 56, 2)) +>NeededInfo : Symbol(NeededInfo, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 52, 45)) +>ToB : Symbol(ToB, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 49, 37)) +>initialize : Symbol(initialize, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 58, 37)) + +const tmp1: MyInfo = null!; +>tmp1 : Symbol(tmp1, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 60, 5)) +>MyInfo : Symbol(MyInfo, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 56, 2)) + +function tmp2(n: N) {} +>tmp2 : Symbol(tmp2, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 60, 27)) +>N : Symbol(N, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 61, 14)) +>NeededInfo : Symbol(NeededInfo, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 52, 45)) +>n : Symbol(n, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 61, 36)) +>N : Symbol(N, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 61, 14)) + +tmp2(tmp1); // uncommenting this line removes a type error from a completely unrelated line ?? +>tmp2 : Symbol(tmp2, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 60, 27)) +>tmp1 : Symbol(tmp1, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 60, 5)) + +class Server {} +>Server : Symbol(Server, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 62, 11)) +>X : Symbol(X, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 64, 13)) +>NeededInfo : Symbol(NeededInfo, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 52, 45)) + +export class MyServer extends Server {} // not assignable error at `MyInfo` +>MyServer : Symbol(MyServer, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 64, 37)) +>Server : Symbol(Server, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 62, 11)) +>MyInfo : Symbol(MyInfo, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts, 56, 2)) + diff --git a/tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign.types b/tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign.types new file mode 100644 index 00000000000..d360372d5aa --- /dev/null +++ b/tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign.types @@ -0,0 +1,168 @@ +=== tests/cases/compiler/varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts === +type Either = Left | Right; +>Either : Either + +class Left { +>Left : Left + + readonly _tag: 'Left' = 'Left' +>_tag : "Left" +>'Left' : "Left" + + readonly _A!: A +>_A : A + + readonly _L!: L +>_L : L + + constructor(readonly value: L) {} +>value : L + + /** The given function is applied if this is a `Right` */ + map(f: (a: A) => B): Either { +>map : (f: (a: A) => B) => Either +>f : (a: A) => B +>a : A + + return this as any +>this as any : any +>this : this + } + ap(fab: Either B>): Either { +>ap : (fab: Either B>) => Either +>fab : Either B> +>a : A + + return null as any +>null as any : any +>null : null + } +} + +class Right { +>Right : Right + + readonly _tag: 'Right' = 'Right' +>_tag : "Right" +>'Right' : "Right" + + readonly _A!: A +>_A : A + + readonly _L!: L +>_L : L + + constructor(readonly value: A) {} +>value : A + + map(f: (a: A) => B): Either { +>map : (f: (a: A) => B) => Either +>f : (a: A) => B +>a : A + + return new Right(f(this.value)) +>new Right(f(this.value)) : Right +>Right : typeof Right +>f(this.value) : B +>f : (a: A) => B +>this.value : A +>this : this +>value : A + } + ap(fab: Either B>): Either { +>ap : (fab: Either B>) => Either +>fab : Either B> +>a : A + + return null as any; +>null as any : any +>null : null + } +} + +class Type { +>Type : Type + + readonly _A!: A; +>_A : A + + readonly _O!: O; +>_O : O + + readonly _I!: I; +>_I : I + + constructor( + /** a unique name for this codec */ + readonly name: string, +>name : string + + /** a custom type guard */ + readonly is: (u: unknown) => u is A, +>is : (u: unknown) => u is A +>u : unknown + + /** succeeds if a value of type I can be decoded to a value of type A */ + readonly validate: (input: I, context: {}[]) => Either<{}[], A>, +>validate : (input: I, context: {}[]) => Either<{}[], A> +>input : I +>context : {}[] + + /** converts a value of type A to a value of type O */ + readonly encode: (a: A) => O +>encode : (a: A) => O +>a : A + + ) {} + /** a version of `validate` with a default context */ + decode(i: I): Either<{}[], A> { return null as any; } +>decode : (i: I) => Either<{}[], A> +>i : I +>null as any : any +>null : null +} + +interface Any extends Type {} + +type TypeOf = C["_A"]; +>TypeOf : C["_A"] + +type ToB = { [k in keyof S]: TypeOf }; +>ToB : ToB + +type ToA = { [k in keyof S]: Type }; +>ToA : ToA + +type NeededInfo = { +>NeededInfo : NeededInfo + + ASchema: ToA; +>ASchema : ToA + +}; + +export type MyInfo = NeededInfo>; +>MyInfo : NeededInfo> +>initialize : any + +const tmp1: MyInfo = null!; +>tmp1 : NeededInfo> +>null! : never +>null : null + +function tmp2(n: N) {} +>tmp2 : >(n: N) => void +>n : N + +tmp2(tmp1); // uncommenting this line removes a type error from a completely unrelated line ?? +>tmp2(tmp1) : any +>tmp2 : >(n: N) => void +>tmp1 : NeededInfo> + +class Server {} +>Server : Server + +export class MyServer extends Server {} // not assignable error at `MyInfo` +>MyServer : MyServer +>Server : Server>> + diff --git a/tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.errors.txt b/tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.errors.txt new file mode 100644 index 00000000000..aba1bc1db66 --- /dev/null +++ b/tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.errors.txt @@ -0,0 +1,79 @@ +tests/cases/compiler/varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts(66,38): error TS2344: Type 'NeededInfo>' does not satisfy the constraint 'NeededInfo<{}>'. + Types of property 'ASchema' are incompatible. + Type 'ToA>' is not assignable to type 'ToA<{}>'. + Type '{}' is not assignable to type 'ToB<{ initialize: any; }>'. + + +==== tests/cases/compiler/varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts (1 errors) ==== + type Either = Left | Right; + + class Left { + readonly _tag: 'Left' = 'Left' + readonly _A!: A + readonly _L!: L + constructor(readonly value: L) {} + /** The given function is applied if this is a `Right` */ + map(f: (a: A) => B): Either { + return this as any + } + ap(fab: Either B>): Either { + return null as any + } + } + + class Right { + readonly _tag: 'Right' = 'Right' + readonly _A!: A + readonly _L!: L + constructor(readonly value: A) {} + map(f: (a: A) => B): Either { + return new Right(f(this.value)) + } + ap(fab: Either B>): Either { + return null as any; + } + } + + class Type { + readonly _A!: A; + readonly _O!: O; + readonly _I!: I; + constructor( + /** a unique name for this codec */ + readonly name: string, + /** a custom type guard */ + readonly is: (u: unknown) => u is A, + /** succeeds if a value of type I can be decoded to a value of type A */ + readonly validate: (input: I, context: {}[]) => Either<{}[], A>, + /** converts a value of type A to a value of type O */ + readonly encode: (a: A) => O + ) {} + /** a version of `validate` with a default context */ + decode(i: I): Either<{}[], A> { return null as any; } + } + + interface Any extends Type {} + + type TypeOf = C["_A"]; + + type ToB = { [k in keyof S]: TypeOf }; + type ToA = { [k in keyof S]: Type }; + + type NeededInfo = { + ASchema: ToA; + }; + + export type MyInfo = NeededInfo>; + + const tmp1: MyInfo = null!; + function tmp2(n: N) {} + // tmp2(tmp1); // uncommenting this line removes a type error from a completely unrelated line ?? (see test 1, needs to behave the same) + + class Server {} + export class MyServer extends Server {} // not assignable error at `MyInfo` + ~~~~~~ +!!! error TS2344: Type 'NeededInfo>' does not satisfy the constraint 'NeededInfo<{}>'. +!!! error TS2344: Types of property 'ASchema' are incompatible. +!!! error TS2344: Type 'ToA>' is not assignable to type 'ToA<{}>'. +!!! error TS2344: Type '{}' is not assignable to type 'ToB<{ initialize: any; }>'. +!!! related TS2728 tests/cases/compiler/varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts:59:39: 'initialize' is declared here. \ No newline at end of file diff --git a/tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.js b/tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.js new file mode 100644 index 00000000000..8a4340ada95 --- /dev/null +++ b/tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.js @@ -0,0 +1,146 @@ +//// [varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts] +type Either = Left | Right; + +class Left { + readonly _tag: 'Left' = 'Left' + readonly _A!: A + readonly _L!: L + constructor(readonly value: L) {} + /** The given function is applied if this is a `Right` */ + map(f: (a: A) => B): Either { + return this as any + } + ap(fab: Either B>): Either { + return null as any + } +} + +class Right { + readonly _tag: 'Right' = 'Right' + readonly _A!: A + readonly _L!: L + constructor(readonly value: A) {} + map(f: (a: A) => B): Either { + return new Right(f(this.value)) + } + ap(fab: Either B>): Either { + return null as any; + } +} + +class Type { + readonly _A!: A; + readonly _O!: O; + readonly _I!: I; + constructor( + /** a unique name for this codec */ + readonly name: string, + /** a custom type guard */ + readonly is: (u: unknown) => u is A, + /** succeeds if a value of type I can be decoded to a value of type A */ + readonly validate: (input: I, context: {}[]) => Either<{}[], A>, + /** converts a value of type A to a value of type O */ + readonly encode: (a: A) => O + ) {} + /** a version of `validate` with a default context */ + decode(i: I): Either<{}[], A> { return null as any; } +} + +interface Any extends Type {} + +type TypeOf = C["_A"]; + +type ToB = { [k in keyof S]: TypeOf }; +type ToA = { [k in keyof S]: Type }; + +type NeededInfo = { + ASchema: ToA; +}; + +export type MyInfo = NeededInfo>; + +const tmp1: MyInfo = null!; +function tmp2(n: N) {} +// tmp2(tmp1); // uncommenting this line removes a type error from a completely unrelated line ?? (see test 1, needs to behave the same) + +class Server {} +export class MyServer extends Server {} // not assignable error at `MyInfo` + +//// [varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.js] +"use strict"; +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +exports.__esModule = true; +var Left = /** @class */ (function () { + function Left(value) { + this.value = value; + this._tag = 'Left'; + } + /** The given function is applied if this is a `Right` */ + Left.prototype.map = function (f) { + return this; + }; + Left.prototype.ap = function (fab) { + return null; + }; + return Left; +}()); +var Right = /** @class */ (function () { + function Right(value) { + this.value = value; + this._tag = 'Right'; + } + Right.prototype.map = function (f) { + return new Right(f(this.value)); + }; + Right.prototype.ap = function (fab) { + return null; + }; + return Right; +}()); +var Type = /** @class */ (function () { + function Type( + /** a unique name for this codec */ + name, + /** a custom type guard */ + is, + /** succeeds if a value of type I can be decoded to a value of type A */ + validate, + /** converts a value of type A to a value of type O */ + encode) { + this.name = name; + this.is = is; + this.validate = validate; + this.encode = encode; + } + /** a version of `validate` with a default context */ + Type.prototype.decode = function (i) { return null; }; + return Type; +}()); +var tmp1 = null; +function tmp2(n) { } +// tmp2(tmp1); // uncommenting this line removes a type error from a completely unrelated line ?? (see test 1, needs to behave the same) +var Server = /** @class */ (function () { + function Server() { + } + return Server; +}()); +var MyServer = /** @class */ (function (_super) { + __extends(MyServer, _super); + function MyServer() { + return _super !== null && _super.apply(this, arguments) || this; + } + return MyServer; +}(Server)); // not assignable error at `MyInfo` +exports.MyServer = MyServer; diff --git a/tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.symbols b/tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.symbols new file mode 100644 index 00000000000..6d8983bd953 --- /dev/null +++ b/tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.symbols @@ -0,0 +1,244 @@ +=== tests/cases/compiler/varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts === +type Either = Left | Right; +>Either : Symbol(Either, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 0, 0)) +>L : Symbol(L, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 0, 12)) +>A : Symbol(A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 0, 14)) +>Left : Symbol(Left, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 0, 45)) +>L : Symbol(L, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 0, 12)) +>A : Symbol(A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 0, 14)) +>Right : Symbol(Right, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 14, 1)) +>L : Symbol(L, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 0, 12)) +>A : Symbol(A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 0, 14)) + +class Left { +>Left : Symbol(Left, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 0, 45)) +>L : Symbol(L, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 2, 11)) +>A : Symbol(A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 2, 13)) + + readonly _tag: 'Left' = 'Left' +>_tag : Symbol(Left._tag, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 2, 18)) + + readonly _A!: A +>_A : Symbol(Left._A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 3, 34)) +>A : Symbol(A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 2, 13)) + + readonly _L!: L +>_L : Symbol(Left._L, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 4, 19)) +>L : Symbol(L, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 2, 11)) + + constructor(readonly value: L) {} +>value : Symbol(Left.value, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 6, 16)) +>L : Symbol(L, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 2, 11)) + + /** The given function is applied if this is a `Right` */ + map(f: (a: A) => B): Either { +>map : Symbol(Left.map, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 6, 37)) +>B : Symbol(B, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 8, 8)) +>f : Symbol(f, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 8, 11)) +>a : Symbol(a, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 8, 15)) +>A : Symbol(A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 2, 13)) +>B : Symbol(B, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 8, 8)) +>Either : Symbol(Either, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 0, 0)) +>L : Symbol(L, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 2, 11)) +>B : Symbol(B, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 8, 8)) + + return this as any +>this : Symbol(Left, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 0, 45)) + } + ap(fab: Either B>): Either { +>ap : Symbol(Left.ap, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 10, 5)) +>B : Symbol(B, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 11, 7)) +>fab : Symbol(fab, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 11, 10)) +>Either : Symbol(Either, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 0, 0)) +>L : Symbol(L, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 2, 11)) +>a : Symbol(a, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 11, 26)) +>A : Symbol(A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 2, 13)) +>B : Symbol(B, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 11, 7)) +>Either : Symbol(Either, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 0, 0)) +>L : Symbol(L, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 2, 11)) +>B : Symbol(B, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 11, 7)) + + return null as any + } +} + +class Right { +>Right : Symbol(Right, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 14, 1)) +>L : Symbol(L, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 16, 12)) +>A : Symbol(A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 16, 14)) + + readonly _tag: 'Right' = 'Right' +>_tag : Symbol(Right._tag, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 16, 19)) + + readonly _A!: A +>_A : Symbol(Right._A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 17, 36)) +>A : Symbol(A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 16, 14)) + + readonly _L!: L +>_L : Symbol(Right._L, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 18, 19)) +>L : Symbol(L, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 16, 12)) + + constructor(readonly value: A) {} +>value : Symbol(Right.value, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 20, 16)) +>A : Symbol(A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 16, 14)) + + map(f: (a: A) => B): Either { +>map : Symbol(Right.map, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 20, 37)) +>B : Symbol(B, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 21, 8)) +>f : Symbol(f, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 21, 11)) +>a : Symbol(a, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 21, 15)) +>A : Symbol(A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 16, 14)) +>B : Symbol(B, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 21, 8)) +>Either : Symbol(Either, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 0, 0)) +>L : Symbol(L, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 16, 12)) +>B : Symbol(B, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 21, 8)) + + return new Right(f(this.value)) +>Right : Symbol(Right, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 14, 1)) +>f : Symbol(f, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 21, 11)) +>this.value : Symbol(Right.value, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 20, 16)) +>this : Symbol(Right, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 14, 1)) +>value : Symbol(Right.value, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 20, 16)) + } + ap(fab: Either B>): Either { +>ap : Symbol(Right.ap, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 23, 5)) +>B : Symbol(B, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 24, 7)) +>fab : Symbol(fab, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 24, 10)) +>Either : Symbol(Either, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 0, 0)) +>L : Symbol(L, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 16, 12)) +>a : Symbol(a, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 24, 26)) +>A : Symbol(A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 16, 14)) +>B : Symbol(B, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 24, 7)) +>Either : Symbol(Either, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 0, 0)) +>L : Symbol(L, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 16, 12)) +>B : Symbol(B, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 24, 7)) + + return null as any; + } +} + +class Type { +>Type : Symbol(Type, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 27, 1)) +>A : Symbol(A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 29, 11)) +>O : Symbol(O, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 29, 13)) +>A : Symbol(A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 29, 11)) +>I : Symbol(I, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 29, 20)) + + readonly _A!: A; +>_A : Symbol(Type._A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 29, 35)) +>A : Symbol(A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 29, 11)) + + readonly _O!: O; +>_O : Symbol(Type._O, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 30, 18)) +>O : Symbol(O, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 29, 13)) + + readonly _I!: I; +>_I : Symbol(Type._I, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 31, 18)) +>I : Symbol(I, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 29, 20)) + + constructor( + /** a unique name for this codec */ + readonly name: string, +>name : Symbol(Type.name, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 33, 14)) + + /** a custom type guard */ + readonly is: (u: unknown) => u is A, +>is : Symbol(Type.is, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 35, 26)) +>u : Symbol(u, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 37, 18)) +>u : Symbol(u, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 37, 18)) +>A : Symbol(A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 29, 11)) + + /** succeeds if a value of type I can be decoded to a value of type A */ + readonly validate: (input: I, context: {}[]) => Either<{}[], A>, +>validate : Symbol(Type.validate, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 37, 40)) +>input : Symbol(input, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 39, 24)) +>I : Symbol(I, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 29, 20)) +>context : Symbol(context, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 39, 33)) +>Either : Symbol(Either, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 0, 0)) +>A : Symbol(A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 29, 11)) + + /** converts a value of type A to a value of type O */ + readonly encode: (a: A) => O +>encode : Symbol(Type.encode, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 39, 68)) +>a : Symbol(a, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 41, 22)) +>A : Symbol(A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 29, 11)) +>O : Symbol(O, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 29, 13)) + + ) {} + /** a version of `validate` with a default context */ + decode(i: I): Either<{}[], A> { return null as any; } +>decode : Symbol(Type.decode, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 42, 6)) +>i : Symbol(i, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 44, 9)) +>I : Symbol(I, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 29, 20)) +>Either : Symbol(Either, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 0, 0)) +>A : Symbol(A, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 29, 11)) +} + +interface Any extends Type {} +>Any : Symbol(Any, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 45, 1)) +>Type : Symbol(Type, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 27, 1)) + +type TypeOf = C["_A"]; +>TypeOf : Symbol(TypeOf, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 47, 44)) +>C : Symbol(C, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 49, 12)) +>Any : Symbol(Any, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 45, 1)) +>C : Symbol(C, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 49, 12)) + +type ToB = { [k in keyof S]: TypeOf }; +>ToB : Symbol(ToB, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 49, 37)) +>S : Symbol(S, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 51, 9)) +>k : Symbol(k, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 51, 29)) +>S : Symbol(S, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 51, 9)) +>TypeOf : Symbol(TypeOf, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 47, 44)) +>S : Symbol(S, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 51, 9)) +>k : Symbol(k, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 51, 29)) + +type ToA = { [k in keyof S]: Type }; +>ToA : Symbol(ToA, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 51, 59)) +>S : Symbol(S, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 52, 9)) +>k : Symbol(k, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 52, 17)) +>S : Symbol(S, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 52, 9)) +>Type : Symbol(Type, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 27, 1)) +>S : Symbol(S, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 52, 9)) +>k : Symbol(k, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 52, 17)) + +type NeededInfo = { +>NeededInfo : Symbol(NeededInfo, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 52, 45)) +>MyNamespaceSchema : Symbol(MyNamespaceSchema, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 54, 16)) + + ASchema: ToA; +>ASchema : Symbol(ASchema, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 54, 43)) +>ToA : Symbol(ToA, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 51, 59)) +>MyNamespaceSchema : Symbol(MyNamespaceSchema, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 54, 16)) + +}; + +export type MyInfo = NeededInfo>; +>MyInfo : Symbol(MyInfo, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 56, 2)) +>NeededInfo : Symbol(NeededInfo, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 52, 45)) +>ToB : Symbol(ToB, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 49, 37)) +>initialize : Symbol(initialize, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 58, 37)) + +const tmp1: MyInfo = null!; +>tmp1 : Symbol(tmp1, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 60, 5)) +>MyInfo : Symbol(MyInfo, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 56, 2)) + +function tmp2(n: N) {} +>tmp2 : Symbol(tmp2, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 60, 27)) +>N : Symbol(N, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 61, 14)) +>NeededInfo : Symbol(NeededInfo, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 52, 45)) +>n : Symbol(n, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 61, 36)) +>N : Symbol(N, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 61, 14)) + +// tmp2(tmp1); // uncommenting this line removes a type error from a completely unrelated line ?? (see test 1, needs to behave the same) + +class Server {} +>Server : Symbol(Server, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 61, 44)) +>X : Symbol(X, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 64, 13)) +>NeededInfo : Symbol(NeededInfo, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 52, 45)) + +export class MyServer extends Server {} // not assignable error at `MyInfo` +>MyServer : Symbol(MyServer, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 64, 37)) +>Server : Symbol(Server, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 61, 44)) +>MyInfo : Symbol(MyInfo, Decl(varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts, 56, 2)) + diff --git a/tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.types b/tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.types new file mode 100644 index 00000000000..02a69f2fab0 --- /dev/null +++ b/tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.types @@ -0,0 +1,165 @@ +=== tests/cases/compiler/varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts === +type Either = Left | Right; +>Either : Either + +class Left { +>Left : Left + + readonly _tag: 'Left' = 'Left' +>_tag : "Left" +>'Left' : "Left" + + readonly _A!: A +>_A : A + + readonly _L!: L +>_L : L + + constructor(readonly value: L) {} +>value : L + + /** The given function is applied if this is a `Right` */ + map(f: (a: A) => B): Either { +>map : (f: (a: A) => B) => Either +>f : (a: A) => B +>a : A + + return this as any +>this as any : any +>this : this + } + ap(fab: Either B>): Either { +>ap : (fab: Either B>) => Either +>fab : Either B> +>a : A + + return null as any +>null as any : any +>null : null + } +} + +class Right { +>Right : Right + + readonly _tag: 'Right' = 'Right' +>_tag : "Right" +>'Right' : "Right" + + readonly _A!: A +>_A : A + + readonly _L!: L +>_L : L + + constructor(readonly value: A) {} +>value : A + + map(f: (a: A) => B): Either { +>map : (f: (a: A) => B) => Either +>f : (a: A) => B +>a : A + + return new Right(f(this.value)) +>new Right(f(this.value)) : Right +>Right : typeof Right +>f(this.value) : B +>f : (a: A) => B +>this.value : A +>this : this +>value : A + } + ap(fab: Either B>): Either { +>ap : (fab: Either B>) => Either +>fab : Either B> +>a : A + + return null as any; +>null as any : any +>null : null + } +} + +class Type { +>Type : Type + + readonly _A!: A; +>_A : A + + readonly _O!: O; +>_O : O + + readonly _I!: I; +>_I : I + + constructor( + /** a unique name for this codec */ + readonly name: string, +>name : string + + /** a custom type guard */ + readonly is: (u: unknown) => u is A, +>is : (u: unknown) => u is A +>u : unknown + + /** succeeds if a value of type I can be decoded to a value of type A */ + readonly validate: (input: I, context: {}[]) => Either<{}[], A>, +>validate : (input: I, context: {}[]) => Either<{}[], A> +>input : I +>context : {}[] + + /** converts a value of type A to a value of type O */ + readonly encode: (a: A) => O +>encode : (a: A) => O +>a : A + + ) {} + /** a version of `validate` with a default context */ + decode(i: I): Either<{}[], A> { return null as any; } +>decode : (i: I) => Either<{}[], A> +>i : I +>null as any : any +>null : null +} + +interface Any extends Type {} + +type TypeOf = C["_A"]; +>TypeOf : C["_A"] + +type ToB = { [k in keyof S]: TypeOf }; +>ToB : ToB + +type ToA = { [k in keyof S]: Type }; +>ToA : ToA + +type NeededInfo = { +>NeededInfo : NeededInfo + + ASchema: ToA; +>ASchema : ToA + +}; + +export type MyInfo = NeededInfo>; +>MyInfo : NeededInfo> +>initialize : any + +const tmp1: MyInfo = null!; +>tmp1 : NeededInfo> +>null! : never +>null : null + +function tmp2(n: N) {} +>tmp2 : >(n: N) => void +>n : N + +// tmp2(tmp1); // uncommenting this line removes a type error from a completely unrelated line ?? (see test 1, needs to behave the same) + +class Server {} +>Server : Server + +export class MyServer extends Server {} // not assignable error at `MyInfo` +>MyServer : MyServer +>Server : Server>> + diff --git a/tests/cases/compiler/varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts b/tests/cases/compiler/varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts new file mode 100644 index 00000000000..c84abda5e56 --- /dev/null +++ b/tests/cases/compiler/varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts @@ -0,0 +1,67 @@ +// @strict: true +type Either = Left | Right; + +class Left { + readonly _tag: 'Left' = 'Left' + readonly _A!: A + readonly _L!: L + constructor(readonly value: L) {} + /** The given function is applied if this is a `Right` */ + map(f: (a: A) => B): Either { + return this as any + } + ap(fab: Either B>): Either { + return null as any + } +} + +class Right { + readonly _tag: 'Right' = 'Right' + readonly _A!: A + readonly _L!: L + constructor(readonly value: A) {} + map(f: (a: A) => B): Either { + return new Right(f(this.value)) + } + ap(fab: Either B>): Either { + return null as any; + } +} + +class Type { + readonly _A!: A; + readonly _O!: O; + readonly _I!: I; + constructor( + /** a unique name for this codec */ + readonly name: string, + /** a custom type guard */ + readonly is: (u: unknown) => u is A, + /** succeeds if a value of type I can be decoded to a value of type A */ + readonly validate: (input: I, context: {}[]) => Either<{}[], A>, + /** converts a value of type A to a value of type O */ + readonly encode: (a: A) => O + ) {} + /** a version of `validate` with a default context */ + decode(i: I): Either<{}[], A> { return null as any; } +} + +interface Any extends Type {} + +type TypeOf = C["_A"]; + +type ToB = { [k in keyof S]: TypeOf }; +type ToA = { [k in keyof S]: Type }; + +type NeededInfo = { + ASchema: ToA; +}; + +export type MyInfo = NeededInfo>; + +const tmp1: MyInfo = null!; +function tmp2(n: N) {} +tmp2(tmp1); // uncommenting this line removes a type error from a completely unrelated line ?? + +class Server {} +export class MyServer extends Server {} // not assignable error at `MyInfo` \ No newline at end of file diff --git a/tests/cases/compiler/varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts b/tests/cases/compiler/varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts new file mode 100644 index 00000000000..14d835e6185 --- /dev/null +++ b/tests/cases/compiler/varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts @@ -0,0 +1,67 @@ +// @strict: true +type Either = Left | Right; + +class Left { + readonly _tag: 'Left' = 'Left' + readonly _A!: A + readonly _L!: L + constructor(readonly value: L) {} + /** The given function is applied if this is a `Right` */ + map(f: (a: A) => B): Either { + return this as any + } + ap(fab: Either B>): Either { + return null as any + } +} + +class Right { + readonly _tag: 'Right' = 'Right' + readonly _A!: A + readonly _L!: L + constructor(readonly value: A) {} + map(f: (a: A) => B): Either { + return new Right(f(this.value)) + } + ap(fab: Either B>): Either { + return null as any; + } +} + +class Type { + readonly _A!: A; + readonly _O!: O; + readonly _I!: I; + constructor( + /** a unique name for this codec */ + readonly name: string, + /** a custom type guard */ + readonly is: (u: unknown) => u is A, + /** succeeds if a value of type I can be decoded to a value of type A */ + readonly validate: (input: I, context: {}[]) => Either<{}[], A>, + /** converts a value of type A to a value of type O */ + readonly encode: (a: A) => O + ) {} + /** a version of `validate` with a default context */ + decode(i: I): Either<{}[], A> { return null as any; } +} + +interface Any extends Type {} + +type TypeOf = C["_A"]; + +type ToB = { [k in keyof S]: TypeOf }; +type ToA = { [k in keyof S]: Type }; + +type NeededInfo = { + ASchema: ToA; +}; + +export type MyInfo = NeededInfo>; + +const tmp1: MyInfo = null!; +function tmp2(n: N) {} +// tmp2(tmp1); // uncommenting this line removes a type error from a completely unrelated line ?? (see test 1, needs to behave the same) + +class Server {} +export class MyServer extends Server {} // not assignable error at `MyInfo` \ No newline at end of file From 17b89653c228358b1fcca8ab6089396f32aff999 Mon Sep 17 00:00:00 2001 From: Gabriela Araujo Britto Date: Tue, 19 Feb 2019 14:20:37 -0800 Subject: [PATCH 081/149] include trailing trivia after expression in getAdjustedEndPosition if endPosition is include --- src/services/textChanges.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/services/textChanges.ts b/src/services/textChanges.ts index 546fddaca14..b8e8ee90ee9 100644 --- a/src/services/textChanges.ts +++ b/src/services/textChanges.ts @@ -195,7 +195,7 @@ namespace ts.textChanges { function getAdjustedEndPosition(sourceFile: SourceFile, node: Node, options: ConfigurableEnd) { const { end } = node; const { endPosition } = options; - if (endPosition === TrailingTriviaOption.Exclude || isExpression(node)) { + if (endPosition === TrailingTriviaOption.Exclude || (isExpression(node) && endPosition !== TrailingTriviaOption.Include)) { return end; } const newEnd = skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true); From edf0cec3ddd7f0f8c7a1b58501668e6b9c70ddd0 Mon Sep 17 00:00:00 2001 From: Gabriela Araujo Britto Date: Tue, 19 Feb 2019 14:22:59 -0800 Subject: [PATCH 082/149] add tests for inherited constructor and method --- ...tToNamedParameters_inheritedConstructor.ts | 21 ++++++++++++++++ ...onvertToNamedParameters_inheritedMethod.ts | 25 +++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters_inheritedConstructor.ts create mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters_inheritedMethod.ts diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters_inheritedConstructor.ts b/tests/cases/fourslash/refactorConvertToNamedParameters_inheritedConstructor.ts new file mode 100644 index 00000000000..743fc7fadb4 --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToNamedParameters_inheritedConstructor.ts @@ -0,0 +1,21 @@ +/// + +////class Foo { +//// /*a*/constructor/*b*/(t: string, s: string) { } +////} +////class Bar extends Foo { } +////var bar = new Bar("a", "b"); +////var foo = new Foo("c", "d"); + +goTo.select("a", "b"); +edit.applyRefactor({ + refactorName: "Convert to named parameters", + actionName: "Convert to named parameters", + actionDescription: "Convert to named parameters", + newContent: `class Foo { + constructor({ t, s }: { t: string; s: string; }) { } +} +class Bar extends Foo { } +var bar = new Bar({ t: "a", s: "b" }); +var foo = new Foo({ t: "c", s: "d" })` +}); \ No newline at end of file diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters_inheritedMethod.ts b/tests/cases/fourslash/refactorConvertToNamedParameters_inheritedMethod.ts new file mode 100644 index 00000000000..3214ea4bf53 --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToNamedParameters_inheritedMethod.ts @@ -0,0 +1,25 @@ +/// + +////class Foo { +//// /*a*/bar/*b*/(t: string, s: string): string { +//// return s + t; +//// } +////} +////class Bar extends Foo { } +////var bar = new Bar(); +////bar.bar("a", "b"); + +goTo.select("a", "b"); +edit.applyRefactor({ + refactorName: "Convert to named parameters", + actionName: "Convert to named parameters", + actionDescription: "Convert to named parameters", + newContent: `class Foo { + bar({ t, s }: { t: string; s: string; }): string { + return s + t; + } +} +class Bar extends Foo { } +var bar = new Bar(); +bar.bar({ t: "a", s: "b" });` +}); \ No newline at end of file From 754f4a45b6148ae6757ef971f92b3249d48ecae2 Mon Sep 17 00:00:00 2001 From: Gabriela Araujo Britto Date: Tue, 19 Feb 2019 14:23:26 -0800 Subject: [PATCH 083/149] refactor expected test output --- ...refactorConvertToNamedParameters_callComments2.ts | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters_callComments2.ts b/tests/cases/fourslash/refactorConvertToNamedParameters_callComments2.ts index e0a78b091fc..37d4e945a2c 100644 --- a/tests/cases/fourslash/refactorConvertToNamedParameters_callComments2.ts +++ b/tests/cases/fourslash/refactorConvertToNamedParameters_callComments2.ts @@ -21,5 +21,15 @@ edit.applyRefactor({ newContent: `function foo({ a, b, rest = [] }: { a: number; b: number; rest?: number[]; }) { return a + b; } -foo({ a: /**a*/ 1, b: /**c*/ 2, rest: [/**e*/ 3, /**g*/ 4] });` +foo( + { + /**a*/ + a: 1, + /**c*/ + b: 2, + rest: [ + /**e*/ + 3, + /**g*/ + 4]});` }); \ No newline at end of file From ee17915801d3e1cf796c7a92861c6b1dc5f4d884 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Tue, 19 Feb 2019 14:30:58 -0800 Subject: [PATCH 084/149] Fix build breaks (#29977) * Some callbacks in watchUtilities werent being strictly checked due to the structural fallback * Add direct dependeny on ms since mocha removed its impl * Manually init stats collection on base runner like mocha.run now does --- package.json | 2 ++ src/compiler/watchUtilities.ts | 10 +++++----- src/testRunner/parallel/host.ts | 4 +++- 3 files changed, 10 insertions(+), 6 deletions(-) diff --git a/package.json b/package.json index f891f99be56..abf7aa17d35 100644 --- a/package.json +++ b/package.json @@ -46,6 +46,7 @@ "@types/minimist": "latest", "@types/mkdirp": "latest", "@types/mocha": "latest", + "@types/ms": "latest", "@types/node": "8.5.5", "@types/q": "latest", "@types/source-map-support": "latest", @@ -74,6 +75,7 @@ "mkdirp": "latest", "mocha": "latest", "mocha-fivemat-progress-reporter": "latest", + "ms": "latest", "plugin-error": "latest", "pretty-hrtime": "^1.0.3", "prex": "^0.4.3", diff --git a/src/compiler/watchUtilities.ts b/src/compiler/watchUtilities.ts index 9bf242e07e8..565af054b8f 100644 --- a/src/compiler/watchUtilities.ts +++ b/src/compiler/watchUtilities.ts @@ -361,9 +361,9 @@ namespace ts { function getWatchFactoryWith(watchLogLevel: WatchLogLevel, log: (s: string) => void, getDetailWatchInfo: GetDetailWatchInfo | undefined, watchFile: (host: WatchFileHost, file: string, callback: FileWatcherCallback, watchPriority: PollingInterval) => FileWatcher, watchDirectory: (host: WatchDirectoryHost, directory: string, callback: DirectoryWatcherCallback, flags: WatchDirectoryFlags) => FileWatcher): WatchFactory { - const createFileWatcher: CreateFileWatcher = getCreateFileWatcher(watchLogLevel, watchFile); + const createFileWatcher: CreateFileWatcher = getCreateFileWatcher(watchLogLevel, watchFile); const createFilePathWatcher: CreateFileWatcher = watchLogLevel === WatchLogLevel.None ? watchFilePath : createFileWatcher; - const createDirectoryWatcher: CreateFileWatcher = getCreateFileWatcher(watchLogLevel, watchDirectory); + const createDirectoryWatcher: CreateFileWatcher = getCreateFileWatcher(watchLogLevel, watchDirectory); return { watchFile: (host, file, callback, pollingInterval, detailInfo1, detailInfo2) => createFileWatcher(host, file, callback, pollingInterval, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo), @@ -402,7 +402,7 @@ namespace ts { } } - function createFileWatcherWithLogging(host: H, file: string, cb: WatchCallback, flags: T, passThrough: V | undefined, detailInfo1: X | undefined, detailInfo2: Y | undefined, addWatch: AddWatch, log: (s: string) => void, watchCaption: string, getDetailWatchInfo: GetDetailWatchInfo | undefined): FileWatcher { + function createFileWatcherWithLogging(host: H, file: string, cb: WatchCallback, flags: T, passThrough: V | undefined, detailInfo1: X | undefined, detailInfo2: Y | undefined, addWatch: AddWatch, log: (s: string) => void, watchCaption: string, getDetailWatchInfo: GetDetailWatchInfo | undefined): FileWatcher { log(`${watchCaption}:: Added:: ${getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo)}`); const watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo); return { @@ -413,7 +413,7 @@ namespace ts { }; } - function createDirectoryWatcherWithLogging(host: H, file: string, cb: WatchCallback, flags: T, passThrough: V | undefined, detailInfo1: X | undefined, detailInfo2: Y | undefined, addWatch: AddWatch, log: (s: string) => void, watchCaption: string, getDetailWatchInfo: GetDetailWatchInfo | undefined): FileWatcher { + function createDirectoryWatcherWithLogging(host: H, file: string, cb: WatchCallback, flags: T, passThrough: V | undefined, detailInfo1: X | undefined, detailInfo2: Y | undefined, addWatch: AddWatch, log: (s: string) => void, watchCaption: string, getDetailWatchInfo: GetDetailWatchInfo | undefined): FileWatcher { const watchInfo = `${watchCaption}:: Added:: ${getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo)}`; log(watchInfo); const start = timestamp(); @@ -432,7 +432,7 @@ namespace ts { }; } - function createFileWatcherWithTriggerLogging(host: H, file: string, cb: WatchCallback, flags: T, passThrough: V | undefined, detailInfo1: X | undefined, detailInfo2: Y | undefined, addWatch: AddWatch, log: (s: string) => void, watchCaption: string, getDetailWatchInfo: GetDetailWatchInfo | undefined): FileWatcher { + function createFileWatcherWithTriggerLogging(host: H, file: string, cb: WatchCallback, flags: T, passThrough: V | undefined, detailInfo1: X | undefined, detailInfo2: Y | undefined, addWatch: AddWatch, log: (s: string) => void, watchCaption: string, getDetailWatchInfo: GetDetailWatchInfo | undefined): FileWatcher { return addWatch(host, file, (fileName, cbOptional) => { const triggerredInfo = `${watchCaption}:: Triggered with ${fileName} ${cbOptional !== undefined ? cbOptional : ""}:: ${getWatchInfo(file, flags, detailInfo1, detailInfo2, getDetailWatchInfo)}`; log(triggerredInfo); diff --git a/src/testRunner/parallel/host.ts b/src/testRunner/parallel/host.ts index 9adf9e7e850..597013ed0d9 100644 --- a/src/testRunner/parallel/host.ts +++ b/src/testRunner/parallel/host.ts @@ -7,7 +7,7 @@ namespace Harness.Parallel.Host { const Base = Mocha.reporters.Base; const color = Base.color; const cursor = Base.cursor; - const ms = require("mocha/lib/ms") as typeof import("mocha/lib/ms"); + const ms = require("ms") as typeof import("ms"); const readline = require("readline") as typeof import("readline"); const os = require("os") as typeof import("os"); const tty = require("tty") as typeof import("tty"); @@ -530,6 +530,8 @@ namespace Harness.Parallel.Host { const replayRunner = new Mocha.Runner(new Mocha.Suite(""), /*delay*/ false); replayRunner.started = true; + const createStatsCollector = require("mocha/lib/stats-collector"); + createStatsCollector(replayRunner); // manually init stats collector like mocha.run would const consoleReporter = new Base(replayRunner); patchStats(consoleReporter.stats); From 7c8c6cf4d085cc934b9fc7777f85808151cef481 Mon Sep 17 00:00:00 2001 From: xiaofa Date: Wed, 20 Feb 2019 18:12:09 +0800 Subject: [PATCH 085/149] fix no space before equal operator in type parameter --- src/services/formatting/rules.ts | 2 +- tests/cases/fourslash/formatTypeParameters.ts | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) create mode 100644 tests/cases/fourslash/formatTypeParameters.ts diff --git a/src/services/formatting/rules.ts b/src/services/formatting/rules.ts index b2dac950323..8d710f87a4e 100644 --- a/src/services/formatting/rules.ts +++ b/src/services/formatting/rules.ts @@ -442,7 +442,7 @@ namespace ts.formatting { case SyntaxKind.ForInStatement: // "in" keyword in [P in keyof T]: T[P] case SyntaxKind.TypeParameter: - return context.currentTokenSpan.kind === SyntaxKind.InKeyword || context.nextTokenSpan.kind === SyntaxKind.InKeyword; + return context.currentTokenSpan.kind === SyntaxKind.InKeyword || context.nextTokenSpan.kind === SyntaxKind.InKeyword || context.currentTokenSpan.kind === SyntaxKind.EqualsToken || context.nextTokenSpan.kind === SyntaxKind.EqualsToken; // Technically, "of" is not a binary operator, but format it the same way as "in" case SyntaxKind.ForOfStatement: return context.currentTokenSpan.kind === SyntaxKind.OfKeyword || context.nextTokenSpan.kind === SyntaxKind.OfKeyword; diff --git a/tests/cases/fourslash/formatTypeParameters.ts b/tests/cases/fourslash/formatTypeParameters.ts new file mode 100644 index 00000000000..a6823a4d0bf --- /dev/null +++ b/tests/cases/fourslash/formatTypeParameters.ts @@ -0,0 +1,8 @@ +/// + +/////**/type Bar = T + + +format.document(); +goTo.marker(); +verify.currentLineContentIs('type Bar = T'); \ No newline at end of file From e40442d46aafbf9ecda1f33b495a2f0457a09a56 Mon Sep 17 00:00:00 2001 From: Gabriela Araujo Britto Date: Wed, 20 Feb 2019 11:13:04 -0800 Subject: [PATCH 086/149] minor refactors --- .../refactors/convertToNamedParameters.ts | 138 +++++++++--------- 1 file changed, 71 insertions(+), 67 deletions(-) diff --git a/src/services/refactors/convertToNamedParameters.ts b/src/services/refactors/convertToNamedParameters.ts index 9c88e5ad337..8d4f3d6e3c9 100644 --- a/src/services/refactors/convertToNamedParameters.ts +++ b/src/services/refactors/convertToNamedParameters.ts @@ -71,8 +71,8 @@ namespace ts.refactor.convertToNamedParameters { } function getGroupedReferences(functionNames: Node[], program: Program, cancellationToken: CancellationToken): GroupedReferences { - const functionRefs = flatMap(functionNames, name => FindAllReferences.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken)); - const groupedReferences = groupReferences(functionRefs); + const functionReferences = flatMap(functionNames, name => FindAllReferences.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken)); + const groupedReferences = groupReferences(functionReferences); return groupedReferences; function groupReferences(referenceEntries: ReadonlyArray | undefined): GroupedReferences { @@ -97,27 +97,27 @@ namespace ts.refactor.convertToNamedParameters { function entryToFunctionCall(entry: FindAllReferences.Entry): CallExpression | NewExpression | undefined { if (entry.kind !== FindAllReferences.EntryKind.Span && entry.node && entry.node.parent) { - const functionRef = entry.node; - const parent = functionRef.parent; + const functionReference = entry.node; + const parent = functionReference.parent; switch (parent.kind) { - // Function call (foo(...)) + // Function call (foo(...) or super(...)) case SyntaxKind.CallExpression: const callExpression = tryCast(parent, isCallExpression); - if (callExpression && callExpression.expression === functionRef) { + if (callExpression && callExpression.expression === functionReference) { return callExpression; } break; // Constructor call (new Foo(...)) case SyntaxKind.NewExpression: const newExpression = tryCast(parent, isNewExpression); - if (newExpression && newExpression.expression === functionRef) { + if (newExpression && newExpression.expression === functionReference) { return newExpression; } break; // Method call (x.foo(...)) case SyntaxKind.PropertyAccessExpression: const propertyAccessExpression = tryCast(parent, isPropertyAccessExpression); - if (propertyAccessExpression && propertyAccessExpression.parent && propertyAccessExpression.name === functionRef) { + if (propertyAccessExpression && propertyAccessExpression.parent && propertyAccessExpression.name === functionReference) { const callExpression = tryCast(propertyAccessExpression.parent, isCallExpression); if (callExpression && callExpression.expression === propertyAccessExpression) { return callExpression; @@ -127,7 +127,7 @@ namespace ts.refactor.convertToNamedParameters { // Method call (x['foo'](...)) case SyntaxKind.ElementAccessExpression: const elementAccessExpression = tryCast(parent, isElementAccessExpression); - if (elementAccessExpression && elementAccessExpression.parent && elementAccessExpression.argumentExpression === functionRef) { + if (elementAccessExpression && elementAccessExpression.parent && elementAccessExpression.argumentExpression === functionReference) { const callExpression = tryCast(elementAccessExpression.parent, isCallExpression); if (callExpression && callExpression.expression === elementAccessExpression) { return callExpression; @@ -173,30 +173,35 @@ namespace ts.refactor.convertToNamedParameters { } function isValidFunctionDeclaration(functionDeclaration: SignatureDeclaration, checker: TypeChecker): functionDeclaration is ValidFunctionDeclaration { + if (!isValidParameterNodeArray(functionDeclaration.parameters)) return false; switch (functionDeclaration.kind) { case SyntaxKind.FunctionDeclaration: case SyntaxKind.MethodDeclaration: - return !!functionDeclaration.name && isPropertyName(functionDeclaration.name) && isValidParameterNodeArray(functionDeclaration.parameters) && !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration); + return !!functionDeclaration.name && !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration); case SyntaxKind.Constructor: if (isClassDeclaration(functionDeclaration.parent)) { - return isValidParameterNodeArray(functionDeclaration.parameters) && !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration); + return !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration); } else { - return isVariableDeclaration(functionDeclaration.parent.parent) && !functionDeclaration.parent.parent.type && isVarConst(functionDeclaration.parent.parent) && isValidParameterNodeArray(functionDeclaration.parameters) && !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration); + return isValidVariableDeclaration(functionDeclaration.parent.parent) && !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration); } case SyntaxKind.FunctionExpression: case SyntaxKind.ArrowFunction: - return isVariableDeclaration(functionDeclaration.parent) && !functionDeclaration.parent.type && isVarConst(functionDeclaration.parent) && isValidParameterNodeArray(functionDeclaration.parameters); + return isValidVariableDeclaration(functionDeclaration.parent); } return false; function isValidParameterNodeArray(parameters: NodeArray): parameters is ValidParameterNodeArray { - return parameters && getRefactorableParametersLength(parameters) > minimumParameterLength && every(parameters, isValidParameterDeclaration); + return getRefactorableParametersLength(parameters) > minimumParameterLength && every(parameters, isValidParameterDeclaration); } function isValidParameterDeclaration(paramDeclaration: ParameterDeclaration): paramDeclaration is ValidParameterDeclaration { return !paramDeclaration.modifiers && !paramDeclaration.decorators && isIdentifier(paramDeclaration.name); } + + function isValidVariableDeclaration(node: Node): node is ValidVariableDeclaration { + return isVariableDeclaration(node) && isVarConst(node) && !node.type; + } } function hasThisParameter(parameters: NodeArray): boolean { @@ -217,10 +222,10 @@ namespace ts.refactor.convertToNamedParameters { return parameters; } - function createNewArgument(functionDeclaration: ValidFunctionDeclaration, args: NodeArray): ObjectLiteralExpression { + function createNewArgument(functionDeclaration: ValidFunctionDeclaration, functionArguments: NodeArray): ObjectLiteralExpression { const parameters = getRefactorableParameters(functionDeclaration.parameters); const hasRestParameter = isRestParameter(last(parameters)); - const nonRestArguments = hasRestParameter ? args.slice(0, parameters.length - 1) : args; + const nonRestArguments = hasRestParameter ? functionArguments.slice(0, parameters.length - 1) : functionArguments; const properties = map(nonRestArguments, (arg, i) => { const property = createPropertyAssignment(getParameterName(parameters[i]), arg); suppressLeadingAndTrailingTrivia(property.initializer); @@ -228,8 +233,8 @@ namespace ts.refactor.convertToNamedParameters { return property; }); - if (hasRestParameter && args.length >= parameters.length) { - const restArguments = args.slice(parameters.length - 1); + if (hasRestParameter && functionArguments.length >= parameters.length) { + const restArguments = functionArguments.slice(parameters.length - 1); const restProperty = createPropertyAssignment(getParameterName(last(parameters)), createArrayLiteral(restArguments)); properties.push(restProperty); } @@ -240,82 +245,83 @@ namespace ts.refactor.convertToNamedParameters { function createNewParameters(functionDeclaration: ValidFunctionDeclaration, program: Program, host: LanguageServiceHost): NodeArray { const refactorableParameters = getRefactorableParameters(functionDeclaration.parameters); - const bindingElements = map( - refactorableParameters, - paramDecl => { - const element = createBindingElement( - /*dotDotDotToken*/ undefined, - /*propertyName*/ undefined, - getParameterName(paramDecl), - isRestParameter(paramDecl) ? createArrayLiteral() : paramDecl.initializer); - - suppressLeadingAndTrailingTrivia(element); - if (paramDecl.initializer && element.initializer) { - copyComments(paramDecl.initializer, element.initializer); - } - - return element; }); - const paramName = createObjectBindingPattern(bindingElements); - const paramType = createParamTypeNode(refactorableParameters); + const bindingElements = map(refactorableParameters, createBindingElementFromParameterDeclaration); + const objectParameterName = createObjectBindingPattern(bindingElements); + const objectParameterType = createParameterTypeNode(refactorableParameters); let objectInitializer: Expression | undefined; + // If every parameter in the original function was optional, add an empty object initializer to the new object parameter if (every(refactorableParameters, param => !!param.initializer || !!param.questionToken)) { objectInitializer = createObjectLiteral(); } - const newParameter = createParameter( + const objectParameter = createParameter( /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, - paramName, + objectParameterName, /*questionToken*/ undefined, - paramType, + objectParameterType, objectInitializer); if (hasThisParameter(functionDeclaration.parameters)) { - const thisParam = functionDeclaration.parameters[0]; - const newThis = createParameter( + const thisParameter = functionDeclaration.parameters[0]; + const newThisParameter = createParameter( /*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, - thisParam.name, + thisParameter.name, /*questionToken*/ undefined, - thisParam.type); + thisParameter.type); - suppressLeadingAndTrailingTrivia(newThis.name); - copyComments(thisParam.name, newThis.name); - if (thisParam.type && newThis.type) { - suppressLeadingAndTrailingTrivia(newThis.type); - copyComments(thisParam.type, newThis.type); + suppressLeadingAndTrailingTrivia(newThisParameter.name); + copyComments(thisParameter.name, newThisParameter.name); + if (thisParameter.type && newThisParameter.type) { + suppressLeadingAndTrailingTrivia(newThisParameter.type); + copyComments(thisParameter.type, newThisParameter.type); } - return createNodeArray([newThis, newParameter]); + return createNodeArray([newThisParameter, objectParameter]); } - return createNodeArray([newParameter]); + return createNodeArray([objectParameter]); - function createParamTypeNode(parameters: NodeArray): TypeLiteralNode { + function createBindingElementFromParameterDeclaration(parameterDeclaration: ValidParameterDeclaration): BindingElement { + const element = createBindingElement( + /*dotDotDotToken*/ undefined, + /*propertyName*/ undefined, + getParameterName(parameterDeclaration), + isRestParameter(parameterDeclaration) ? createArrayLiteral() : parameterDeclaration.initializer); + + suppressLeadingAndTrailingTrivia(element); + if (parameterDeclaration.initializer && element.initializer) { + copyComments(parameterDeclaration.initializer, element.initializer); + } + return element; + } + + function createParameterTypeNode(parameters: NodeArray): TypeLiteralNode { const members = map(parameters, createPropertySignatureFromParameterDeclaration); - const typeNode = addEmitFlags(createTypeLiteralNode(members), EmitFlags.SingleLine); // TODO: add single line option to createTypeLiteralNode + const typeNode = addEmitFlags(createTypeLiteralNode(members), EmitFlags.SingleLine); return typeNode; } - function createPropertySignatureFromParameterDeclaration(paramDeclaration: ValidParameterDeclaration): PropertySignature { - let paramType = paramDeclaration.type; - if (!paramType && (paramDeclaration.initializer || isRestParameter(paramDeclaration))) { - paramType = getTypeNode(paramDeclaration); + function createPropertySignatureFromParameterDeclaration(parameterDeclaration: ValidParameterDeclaration): PropertySignature { + let parameterType = parameterDeclaration.type; + if (!parameterType && (parameterDeclaration.initializer || isRestParameter(parameterDeclaration))) { + parameterType = getTypeNode(parameterDeclaration); } const propertySignature = createPropertySignature( /*modifiers*/ undefined, - getParameterName(paramDeclaration), - paramDeclaration.initializer || isRestParameter(paramDeclaration) ? createToken(SyntaxKind.QuestionToken) : paramDeclaration.questionToken, - paramType, + getParameterName(parameterDeclaration), + parameterDeclaration.initializer || isRestParameter(parameterDeclaration) ? createToken(SyntaxKind.QuestionToken) : parameterDeclaration.questionToken, + parameterType, /*initializer*/ undefined); suppressLeadingAndTrailingTrivia(propertySignature); - copyComments(paramDeclaration.name, propertySignature.name); - if (paramDeclaration.type && propertySignature.type) { - copyComments(paramDeclaration.type, propertySignature.type); + copyComments(parameterDeclaration.name, propertySignature.name); + if (parameterDeclaration.type && propertySignature.type) { + copyComments(parameterDeclaration.type, propertySignature.type); } return propertySignature; @@ -359,15 +365,13 @@ namespace ts.refactor.convertToNamedParameters { case SyntaxKind.MethodDeclaration: return [functionDeclaration.name]; case SyntaxKind.Constructor: - const ctrKeyword = findChildOfKind(functionDeclaration, SyntaxKind.ConstructorKeyword, functionDeclaration.getSourceFile()); - let name: Node; + const ctrKeyword = findChildOfKind(functionDeclaration, SyntaxKind.ConstructorKeyword, functionDeclaration.getSourceFile())!; switch (functionDeclaration.parent.kind) { case SyntaxKind.ClassDeclaration: - return [ctrKeyword!]; + return [ctrKeyword]; case SyntaxKind.ClassExpression: - name = functionDeclaration.parent.parent.name; - if (ctrKeyword) return [ctrKeyword, name]; - return [name]; + const name = functionDeclaration.parent.parent.name; + return [ctrKeyword, name]; default: return Debug.assertNever(functionDeclaration.parent); } case SyntaxKind.ArrowFunction: From b67f2d6bdfd7244d1f98c98b6038d7f3280abdc4 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Wed, 20 Feb 2019 15:32:15 -0800 Subject: [PATCH 087/149] Remove jake (hopefully for real this time) (#29085) * Remove jake (hopefully for real this time) * Fix gulpfile non-lkg build, add sanity-check build to posttest on CI, accept older baseline style to go with lkgd build * More docs/scripts jake -> gulp --- .github/pull_request_template.md | 2 +- CONTRIBUTING.md | 28 +- Gulpfile.js | 4 +- Jakefile.js | 860 ------------------ README.md | 26 +- lib/README.md | 2 +- package.json | 15 +- scripts/bisect-test.ts | 1 + scripts/build/tests.js | 13 +- scripts/hooks/post-checkout | 2 +- scripts/open-user-pr.ts | 2 +- .../reference/api/tsserverlibrary.d.ts | 2 +- 12 files changed, 54 insertions(+), 903 deletions(-) delete mode 100644 Jakefile.js diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index daec1666314..2365098deb9 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -5,7 +5,7 @@ Here's a checklist you might find useful. * [ ] There is an associated issue that is labeled 'Bug' or 'help wanted' or is in the Community milestone * [ ] Code is up-to-date with the `master` branch -* [ ] You've successfully run `jake runtests` locally +* [ ] You've successfully run `gulp runtests` locally * [ ] You've signed the CLA * [ ] There are new or updated unit tests validating the change diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 31cfb858089..4b58cc2875a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -104,7 +104,7 @@ Any changes should be made to [src/lib](https://github.com/Microsoft/TypeScript/ Library files in `built/local/` are updated automatically by running the standard build task: ```sh -jake +gulp ``` The files in `lib/` are used to bootstrap compilation and usually **should not** be updated unless publishing a new version or updating the LKG. @@ -115,49 +115,49 @@ The files `src/lib/dom.generated.d.ts` and `src/lib/webworker.generated.d.ts` bo ## Running the Tests -To run all tests, invoke the `runtests-parallel` target using jake: +To run all tests, invoke the `runtests-parallel` target using gulp: ```Shell -jake runtests-parallel +gulp runtests-parallel ``` This will run all tests; to run only a specific subset of tests, use: ```Shell -jake runtests tests= +gulp runtests --tests= ``` e.g. to run all compiler baseline tests: ```Shell -jake runtests tests=compiler +gulp runtests --tests=compiler ``` or to run a specific test: `tests\cases\compiler\2dArrays.ts` ```Shell -jake runtests tests=2dArrays +gulp runtests --tests=2dArrays ``` ## Debugging the tests -To debug the tests, invoke the `runtests-browser` task from jake. +To debug the tests, invoke the `runtests-browser` task from gulp. You will probably only want to debug one test at a time: ```Shell -jake runtests-browser tests=2dArrays +gulp runtests-browser --tests=2dArrays ``` You can specify which browser to use for debugging. Currently Chrome and IE are supported: ```Shell -jake runtests-browser tests=2dArrays browser=chrome +gulp runtests-browser --tests=2dArrays --browser=chrome ``` -You can debug with VS Code or Node instead with `jake runtests inspect=true`: +You can debug with VS Code or Node instead with `gulp runtests --inspect=true`: ```Shell -jake runtests tests=2dArrays inspect=true +gulp runtests --tests=2dArrays --inspect=true ``` ## Adding a Test @@ -197,13 +197,13 @@ Compiler testcases generate baselines that track the emitted `.js`, the errors p When a change in the baselines is detected, the test will fail. To inspect changes vs the expected baselines, use ```Shell -jake diff +gulp diff ``` After verifying that the changes in the baselines are correct, run ```Shell -jake baseline-accept +gulp baseline-accept ``` to establish the new baselines as the desired behavior. This will change the files in `tests\baselines\reference`, which should be included as part of your commit. It's important to carefully validate changes in the baselines. @@ -211,6 +211,6 @@ to establish the new baselines as the desired behavior. This will change the fil ## Localization All strings the user may see are stored in [`diagnosticMessages.json`](./src/compiler/diagnosticMessages.json). -If you make changes to it, run `jake generate-diagnostics` to push them to the `Diagnostic` interface in `diagnosticInformationMap.generated.ts`. +If you make changes to it, run `gulp generate-diagnostics` to push them to the `Diagnostic` interface in `diagnosticInformationMap.generated.ts`. See [coding guidelines on diagnostic messages](https://github.com/Microsoft/TypeScript/wiki/Coding-guidelines#diagnostic-messages). diff --git a/Gulpfile.js b/Gulpfile.js index 7d31e0a6137..3367010f6bd 100644 --- a/Gulpfile.js +++ b/Gulpfile.js @@ -232,7 +232,7 @@ task("watch-tsserver").flags = { " --built": "Compile using the built version of the compiler." } -task("min", series(lkgPreBuild, parallel(buildTsc, buildServer))); +task("min", series(preBuild, parallel(buildTsc, buildServer))); task("min").description = "Builds only tsc and tsserver"; task("min").flags = { " --built": "Compile using the built version of the compiler." @@ -375,7 +375,7 @@ task("lint").flags = { const buildFoldStart = async () => { if (fold.isTravis()) console.log(fold.start("build")); }; const buildFoldEnd = async () => { if (fold.isTravis()) console.log(fold.end("build")); }; -task("local", series(buildFoldStart, lkgPreBuild, parallel(localize, buildTsc, buildServer, buildServices, buildLssl), buildFoldEnd)); +task("local", series(buildFoldStart, preBuild, parallel(localize, buildTsc, buildServer, buildServices, buildLssl), buildFoldEnd)); task("local").description = "Builds the full compiler and services"; task("local").flags = { " --built": "Compile using the built version of the compiler." diff --git a/Jakefile.js b/Jakefile.js deleted file mode 100644 index 18f4aa56f8d..00000000000 --- a/Jakefile.js +++ /dev/null @@ -1,860 +0,0 @@ -// This file contains the build logic for the public repo -// @ts-check -/// - -const fs = require("fs"); -const os = require("os"); -const path = require("path"); -const fold = require("travis-fold"); -const ts = require("./lib/typescript"); -const del = require("del"); -const { getDirSize, needsUpdate, flatten } = require("./scripts/build/utils"); -const { base64VLQFormatEncode } = require("./scripts/build/sourcemaps"); - -// add node_modules to path so we don't need global modules, prefer the modules by adding them first -var nodeModulesPathPrefix = path.resolve("./node_modules/.bin/") + path.delimiter; -if (process.env.path !== undefined) { - process.env.path = nodeModulesPathPrefix + process.env.path; -} -else if (process.env.PATH !== undefined) { - process.env.PATH = nodeModulesPathPrefix + process.env.PATH; -} - -const host = process.env.TYPESCRIPT_HOST || process.env.host || "node"; - -const defaultTestTimeout = 40000; -const useBuilt = - (process.env.USE_BUILT === "true" || process.env.CI === "true") ? true : - process.env.LKG === "true" ? false : - false; - -let useDebugMode = true; - -const TaskNames = { - local: "local", - runtests: "runtests", - runtestsParallel: "runtests-parallel", - buildRules: "build-rules", - clean: "clean", - lib: "lib", - buildFoldStart: "build-fold-start", - buildFoldEnd: "build-fold-end", - generateDiagnostics: "generate-diagnostics", - coreBuild: "core-build", - tsc: "tsc", - lkg: "LKG", - release: "release", - lssl: "lssl", - lint: "lint", - scripts: "scripts", - localize: "localize", - configureInsiders: "configure-insiders", - publishInsiders: "publish-insiders", - configureNightly: "configure-nightly", - publishNightly: "publish-nightly", - help: "help" -}; - -const Paths = {}; -Paths.lkg = "lib"; -Paths.lkgCompiler = "lib/tsc.js"; -Paths.built = "built"; -Paths.builtLocal = "built/local"; -Paths.builtLocalCompiler = "built/local/tsc.js"; -Paths.builtLocalTSServer = "built/local/tsserver.js"; -Paths.builtLocalRun = "built/local/run.js"; -Paths.releaseCompiler = "built/local/tsc.release.js"; -Paths.typesMapOutput = "built/local/typesMap.json"; -Paths.typescriptFile = "built/local/typescript.js"; -Paths.servicesFile = "built/local/typescriptServices.js"; -Paths.servicesDefinitionFile = "built/local/typescriptServices.d.ts"; -Paths.servicesOutFile = "built/local/typescriptServices.out.js"; -Paths.servicesDefinitionOutFile = "built/local/typescriptServices.out.d.ts"; -Paths.typescriptDefinitionFile = "built/local/typescript.d.ts"; -Paths.typescriptStandaloneDefinitionFile = "built/local/typescript_standalone.d.ts"; -Paths.tsserverLibraryFile = "built/local/tsserverlibrary.js"; -Paths.tsserverLibraryDefinitionFile = "built/local/tsserverlibrary.d.ts"; -Paths.tsserverLibraryOutFile = "built/local/tsserverlibrary.out.js"; -Paths.tsserverLibraryDefinitionOutFile = "built/local/tsserverlibrary.out.d.ts"; -Paths.baselines = {}; -Paths.baselines.local = "tests/baselines/local"; -Paths.baselines.localTest262 = "tests/baselines/test262/local"; -Paths.baselines.localRwc = "internal/baselines/rwc/local"; -Paths.baselines.reference = "tests/baselines/reference"; -Paths.baselines.referenceTest262 = "tests/baselines/test262/reference"; -Paths.baselines.referenceRwc = "internal/baselines/rwc/reference"; -Paths.copyright = "CopyrightNotice.txt"; -Paths.thirdParty = "ThirdPartyNoticeText.txt"; -Paths.processDiagnosticMessagesJs = "scripts/processDiagnosticMessages.js"; -Paths.diagnosticInformationMap = "src/compiler/diagnosticInformationMap.generated.ts"; -Paths.diagnosticMessagesJson = "src/compiler/diagnosticMessages.json"; -Paths.diagnosticGeneratedJson = "src/compiler/diagnosticMessages.generated.json"; -Paths.builtDiagnosticGeneratedJson = "built/local/diagnosticMessages.generated.json"; -Paths.lcl = "src/loc/lcl" -Paths.locLcg = "built/local/enu/diagnosticMessages.generated.json.lcg"; -Paths.generatedLCGFile = path.join(Paths.builtLocal, "enu", "diagnosticMessages.generated.json.lcg"); -Paths.library = "src/lib"; -Paths.srcServer = "src/server"; -Paths.scripts = {}; -Paths.scripts.generateLocalizedDiagnosticMessages = "scripts/generateLocalizedDiagnosticMessages.js"; -Paths.scripts.processDiagnosticMessages = "scripts/processDiagnosticMessages.js"; -Paths.scripts.produceLKG = "scripts/produceLKG.js"; -Paths.scripts.configurePrerelease = "scripts/configurePrerelease.js"; -Paths.packageJson = "package.json"; -Paths.versionFile = "src/compiler/core.ts"; - -const ConfigFileFor = { - tsc: "src/tsc", - tscRelease: "src/tsc/tsconfig.release.json", - tsserver: "src/tsserver", - runjs: "src/testRunner", - lint: "scripts/tslint", - scripts: "scripts", - all: "src", - typescriptServices: "built/local/typescriptServices.tsconfig.json", - tsserverLibrary: "built/local/tsserverlibrary.tsconfig.json", -}; - -const ExpectedLKGFiles = [ - "tsc.js", - "tsserver.js", - "typescriptServices.js", - "typescriptServices.d.ts", - "typescript.js", - "typescript.d.ts", - "cancellationToken.js", - "typingsInstaller.js", - "protocol.d.ts", - "watchGuard.js" -]; - -directory(Paths.builtLocal); - -// Local target to build the compiler and services -desc("Builds the full compiler and services"); -task(TaskNames.local, [ - TaskNames.buildFoldStart, - TaskNames.coreBuild, - Paths.servicesDefinitionFile, - Paths.typescriptFile, - Paths.typescriptDefinitionFile, - Paths.typescriptStandaloneDefinitionFile, - Paths.tsserverLibraryDefinitionFile, - TaskNames.localize, - TaskNames.buildFoldEnd -]); - -task("default", [TaskNames.local]); - -const RunTestsPrereqs = [TaskNames.lib, Paths.servicesDefinitionFile, Paths.typescriptDefinitionFile, Paths.tsserverLibraryDefinitionFile]; -desc("Runs all the tests in parallel using the built run.js file. Optional arguments are: t[ests]=category1|category2|... i[nspect]=true."); -task(TaskNames.runtestsParallel, RunTestsPrereqs, function () { - tsbuild([ConfigFileFor.runjs], true, () => { - runConsoleTests("min", /*parallel*/ true); - }); -}, { async: true }); - -desc("Runs all the tests in parallel using the built run.js file. Optional arguments are: t[ests]=category1|category2|... i[nspect]=true."); -task(TaskNames.runtests, RunTestsPrereqs, function () { - tsbuild([ConfigFileFor.runjs], true, () => { - runConsoleTests('mocha-fivemat-progress-reporter', /*runInParallel*/ false); - }); -}, { async: true }); - -desc("Generates a diagnostic file in TypeScript based on an input JSON file"); -task(TaskNames.generateDiagnostics, [Paths.diagnosticInformationMap]); - -const libraryTargets = getLibraryTargets(); -desc("Builds the library targets"); -task(TaskNames.lib, libraryTargets); - -desc("Builds internal scripts"); -task(TaskNames.scripts, [TaskNames.coreBuild], function() { - tsbuild([ConfigFileFor.scripts], true, () => { - complete(); - }); -}, { async: true }); - -task(Paths.releaseCompiler, function () { - tsbuild([ConfigFileFor.tscRelease], true, () => { - complete(); - }); -}, { async: true }); - -// Makes a new LKG. This target does not build anything, but errors if not all the outputs are present in the built/local directory -desc("Makes a new LKG out of the built js files"); -task(TaskNames.lkg, [ - TaskNames.scripts, - TaskNames.release, - TaskNames.local, - Paths.servicesDefinitionFile, - Paths.typescriptFile, - Paths.typescriptDefinitionFile, - Paths.typescriptStandaloneDefinitionFile, - Paths.tsserverLibraryDefinitionFile, - Paths.releaseCompiler, - ...libraryTargets -], () => { - const sizeBefore = getDirSize(Paths.lkg); - - exec(`${host} ${Paths.scripts.produceLKG}`, () => { - const sizeAfter = getDirSize(Paths.lkg); - if (sizeAfter > (sizeBefore * 1.10)) { - throw new Error("The lib folder increased by 10% or more. This likely indicates a bug."); - } - - complete(); - }); -}, { async: true }); - -desc("Makes the most recent test results the new baseline, overwriting the old baseline"); -task("baseline-accept", function () { - acceptBaseline(Paths.baselines.local, Paths.baselines.reference); -}); - -desc("Makes the most recent rwc test results the new baseline, overwriting the old baseline"); -task("baseline-accept-rwc", function () { - acceptBaseline(Paths.baselines.localRwc, Paths.baselines.referenceRwc); -}); - -desc("Makes the most recent test262 test results the new baseline, overwriting the old baseline"); -task("baseline-accept-test262", function () { - acceptBaseline(Paths.baselines.localTest262, Paths.baselines.referenceTest262); -}); - -desc("Runs tslint on the compiler sources. Optional arguments are: f[iles]=regex"); -task(TaskNames.lint, [TaskNames.buildRules], () => { - if (fold.isTravis()) console.log(fold.start("lint")); - function lint(project, cb) { - const fix = process.env.fix || process.env.f; - const cmd = `node node_modules/tslint/bin/tslint --project ${project} --formatters-dir ./built/local/tslint/formatters --format autolinkableStylish${fix ? " --fix" : ""}`; - exec(cmd, cb); - } - lint("scripts/tslint/tsconfig.json", () => lint("src/tsconfig-base.json", () => { - if (fold.isTravis()) console.log(fold.end("lint")); - complete(); - })); -}, { async: true }); - -desc("Diffs the compiler baselines using the diff tool specified by the 'DIFF' environment variable"); -task('diff', function () { - var cmd = `"${getDiffTool()}" ${Paths.baselines.reference} ${Paths.baselines.local}`; - exec(cmd); -}, { async: true }); - -desc("Diffs the RWC baselines using the diff tool specified by the 'DIFF' environment variable"); -task('diff-rwc', function () { - var cmd = `"${getDiffTool()}" ${Paths.baselines.referenceRwc} ${Paths.baselines.localRwc}`; - exec(cmd); -}, { async: true }); - -task(TaskNames.configureNightly, [TaskNames.scripts], function () { - const cmd = `${host} ${Paths.scripts.configurePrerelease} dev ${Paths.packageJson} ${Paths.versionFile}`; - exec(cmd, () => complete()); -}, { async: true }); - -desc("Configure, build, test, and publish the nightly release."); -task(TaskNames.publishNightly, [TaskNames.coreBuild, TaskNames.configureNightly, TaskNames.lkg, "setDebugMode", "runtests-parallel"], function () { - var cmd = "npm publish --tag next"; - exec(cmd, () => complete()); -}, { async: true }); - -task(TaskNames.help, function() { - var cmd = "jake --tasks"; - exec(cmd, () => complete()); -}) - -task(TaskNames.configureInsiders, [TaskNames.scripts], function () { - const cmd = `${host} ${Paths.scripts.configurePrerelease} insiders ${Paths.packageJson} ${Paths.versionFile}`; - exec(cmd, () => complete()); -}, { async: true }); - -desc("Configure, build, test, and publish the insiders release."); -task(TaskNames.publishInsiders, [TaskNames.coreBuild, TaskNames.configureInsiders, TaskNames.lkg, "setDebugMode", "runtests-parallel"], function () { - var cmd = "npm publish --tag insiders"; - exec(cmd, () => complete()); -}, { async: true }); - -desc("Sets the release mode flag"); -task("release", function () { - useDebugMode = false; -}); - -desc("Clears the release mode flag"); -task("setDebugMode", function () { - useDebugMode = true; -}); - -desc("Generates localized diagnostic messages"); -task(TaskNames.localize, [Paths.generatedLCGFile]); - -desc("Emit the start of the build fold"); -task(TaskNames.buildFoldStart, [], function () { - if (fold.isTravis()) console.log(fold.start("build")); -}); - -desc("Emit the end of the build fold"); -task(TaskNames.buildFoldEnd, [], function () { - if (fold.isTravis()) console.log(fold.end("build")); -}); - -desc("Compiles tslint rules to js"); -task(TaskNames.buildRules, [], function () { - tsbuild(ConfigFileFor.lint, !useBuilt, () => complete()); -}, { async: true }); - -desc("Cleans the compiler output, declare files, and tests"); -task(TaskNames.clean, function () { - jake.rmRf(Paths.built); -}); - -desc("Generates the LCG file for localization"); -task("localize", [Paths.generatedLCGFile]); - -task(TaskNames.tsc, [Paths.diagnosticInformationMap, TaskNames.lib], function () { - tsbuild(ConfigFileFor.tsc, true, () => { - complete(); - }); -}, { async: true }); - -task(TaskNames.coreBuild, [Paths.diagnosticInformationMap, TaskNames.lib], function () { - tsbuild(ConfigFileFor.all, true, () => { - complete(); - }); -}, { async: true }); - -file(Paths.diagnosticMessagesJson); - -file(Paths.typesMapOutput, /** @type {*} */(function () { - var content = readFileSync(path.join(Paths.srcServer, 'typesMap.json')); - // Validate that it's valid JSON - try { - JSON.parse(content); - } catch (e) { - console.log("Parse error in typesMap.json: " + e); - } - fs.writeFileSync(Paths.typesMapOutput, content); -})); - -file(Paths.builtDiagnosticGeneratedJson, [Paths.diagnosticGeneratedJson], function () { - if (fs.existsSync(Paths.builtLocal)) { - jake.cpR(Paths.diagnosticGeneratedJson, Paths.builtDiagnosticGeneratedJson); - } -}); - -// Localized diagnostics -file(Paths.generatedLCGFile, [TaskNames.scripts, Paths.diagnosticInformationMap, Paths.diagnosticGeneratedJson], function () { - const cmd = `${host} ${Paths.scripts.generateLocalizedDiagnosticMessages} ${Paths.lcl} ${Paths.builtLocal} ${Paths.diagnosticGeneratedJson}` - exec(cmd, complete); -}, { async: true }); - - -// The generated diagnostics map; built for the compiler and for the 'generate-diagnostics' task -file(Paths.diagnosticInformationMap, [Paths.diagnosticMessagesJson], function () { - tsbuild(ConfigFileFor.scripts, true, () => { - const cmd = `${host} ${Paths.scripts.processDiagnosticMessages} ${Paths.diagnosticMessagesJson}`; - exec(cmd, complete); - }); -}, { async: true }); - -file(ConfigFileFor.tsserverLibrary, [], function () { - flatten("src/tsserver/tsconfig.json", ConfigFileFor.tsserverLibrary, { - exclude: ["src/tsserver/server.ts"], - compilerOptions: { - "removeComments": false, - "stripInternal": true, - "declaration": true, - "outFile": "tsserverlibrary.out.js" - } - }) -}); - -// tsserverlibrary.js -// tsserverlibrary.d.ts -file(Paths.tsserverLibraryFile, [TaskNames.coreBuild, ConfigFileFor.tsserverLibrary], function() { - tsbuild(ConfigFileFor.tsserverLibrary, !useBuilt, () => { - if (needsUpdate([Paths.tsserverLibraryOutFile, Paths.tsserverLibraryDefinitionOutFile], [Paths.tsserverLibraryFile, Paths.tsserverLibraryDefinitionFile])) { - const copyright = readFileSync(Paths.copyright); - - let libraryDefinitionContent = readFileSync(Paths.tsserverLibraryDefinitionOutFile); - libraryDefinitionContent = copyright + removeConstModifierFromEnumDeclarations(libraryDefinitionContent); - libraryDefinitionContent += "\nexport = ts;\nexport as namespace ts;"; - fs.writeFileSync(Paths.tsserverLibraryDefinitionFile, libraryDefinitionContent, "utf8"); - - let libraryContent = readFileSync(Paths.tsserverLibraryOutFile); - libraryContent = copyright + libraryContent; - fs.writeFileSync(Paths.tsserverLibraryFile, libraryContent, "utf8"); - - // adjust source map for tsserverlibrary.js - let libraryMapContent = readFileSync(Paths.tsserverLibraryOutFile + ".map"); - const map = JSON.parse(libraryMapContent); - const lineStarts = /**@type {*}*/(ts).computeLineStarts(copyright); - let prependMappings = ""; - for (let i = 1; i < lineStarts.length; i++) { - prependMappings += ";"; - } - - const offset = copyright.length - lineStarts[lineStarts.length - 1]; - if (offset > 0) { - prependMappings += base64VLQFormatEncode(offset) + ","; - } - - const outputMap = { - version: map.version, - file: map.file, - sources: map.sources, - sourceRoot: map.sourceRoot, - mappings: prependMappings + map.mappings, - names: map.names, - sourcesContent: map.sourcesContent - }; - - libraryMapContent = JSON.stringify(outputMap); - fs.writeFileSync(Paths.tsserverLibraryFile + ".map", libraryMapContent); - } - complete(); - }); -}, { async: true }); -task(Paths.tsserverLibraryDefinitionFile, [Paths.tsserverLibraryFile]); - -file(ConfigFileFor.typescriptServices, [], function () { - flatten("src/services/tsconfig.json", ConfigFileFor.typescriptServices, { - compilerOptions: { - "removeComments": false, - "stripInternal": true, - "declarationMap": false, - "outFile": "typescriptServices.out.js" - } - }); -}); - -// typescriptServices.js -// typescriptServices.d.ts -file(Paths.servicesFile, [TaskNames.coreBuild, ConfigFileFor.typescriptServices], function() { - tsbuild(ConfigFileFor.typescriptServices, !useBuilt, () => { - if (needsUpdate([Paths.servicesOutFile, Paths.servicesDefinitionOutFile], [Paths.servicesFile, Paths.servicesDefinitionFile])) { - const copyright = readFileSync(Paths.copyright); - - let servicesDefinitionContent = readFileSync(Paths.servicesDefinitionOutFile); - servicesDefinitionContent = copyright + removeConstModifierFromEnumDeclarations(servicesDefinitionContent); - fs.writeFileSync(Paths.servicesDefinitionFile, servicesDefinitionContent, "utf8"); - - let servicesContent = readFileSync(Paths.servicesOutFile); - servicesContent = copyright + servicesContent; - fs.writeFileSync(Paths.servicesFile, servicesContent, "utf8"); - - // adjust source map for typescriptServices.js - let servicesMapContent = readFileSync(Paths.servicesOutFile + ".map"); - const map = JSON.parse(servicesMapContent); - const lineStarts = /**@type {*}*/(ts).computeLineStarts(copyright); - let prependMappings = ""; - for (let i = 1; i < lineStarts.length; i++) { - prependMappings += ";"; - } - - const offset = copyright.length - lineStarts[lineStarts.length - 1]; - if (offset > 0) { - prependMappings += base64VLQFormatEncode(offset) + ","; - } - - const outputMap = { - version: map.version, - file: map.file, - sources: map.sources, - sourceRoot: map.sourceRoot, - mappings: prependMappings + map.mappings, - names: map.names, - sourcesContent: map.sourcesContent - }; - - servicesMapContent = JSON.stringify(outputMap); - fs.writeFileSync(Paths.servicesFile + ".map", servicesMapContent); - } - - complete(); - }); -}, { async: true }); -task(Paths.servicesDefinitionFile, [Paths.servicesFile]); - -// typescript.js -// typescript.d.ts -file(Paths.typescriptFile, [Paths.servicesFile], function() { - if (needsUpdate([Paths.servicesFile, Paths.servicesDefinitionFile], [Paths.typescriptFile, Paths.typescriptDefinitionFile])) { - jake.cpR(Paths.servicesFile, Paths.typescriptFile); - if (fs.existsSync(Paths.servicesFile + ".map")) { - jake.cpR(Paths.servicesFile + ".map", Paths.typescriptFile + ".map"); - } - const content = readFileSync(Paths.servicesDefinitionFile); - fs.writeFileSync(Paths.typescriptDefinitionFile, content + "\r\nexport = ts;", { encoding: "utf-8" }); - } -}); -task(Paths.typescriptDefinitionFile, [Paths.typescriptFile]); - -// typescript_standalone.d.ts -file(Paths.typescriptStandaloneDefinitionFile, [Paths.servicesDefinitionFile], function() { - if (needsUpdate(Paths.servicesDefinitionFile, Paths.typescriptStandaloneDefinitionFile)) { - const content = readFileSync(Paths.servicesDefinitionFile); - fs.writeFileSync(Paths.typescriptStandaloneDefinitionFile, content.replace(/declare (namespace|module) ts(\..+)? \{/g, 'declare module "typescript" {'), { encoding: "utf-8"}); - } -}); - -function getLibraryTargets() { - /** @type {{ libs: string[], paths?: Record, sources?: Record }} */ - const libraries = readJson("./src/lib/libs.json"); - return libraries.libs.map(function (lib) { - const relativeSources = ["header.d.ts"].concat(libraries.sources && libraries.sources[lib] || [lib + ".d.ts"]); - const relativeTarget = libraries.paths && libraries.paths[lib] || ("lib." + lib + ".d.ts"); - const sources = [Paths.copyright].concat(relativeSources.map(s => path.join(Paths.library, s))); - const target = path.join(Paths.builtLocal, relativeTarget); - file(target, [Paths.builtLocal].concat(sources), function () { - concatenateFiles(target, sources); - }); - return target; - }); -} - -function runConsoleTests(defaultReporter, runInParallel) { - var dirty = process.env.dirty; - if (!dirty) { - cleanTestDirs(); - } - - let testTimeout = process.env.timeout || defaultTestTimeout; - const inspect = process.env.inspect || process.env["inspect-brk"] || process.env.i; - const runners = process.env.runners || process.env.runner || process.env.ru; - const tests = process.env.test || process.env.tests || process.env.t; - const light = process.env.light === undefined || process.env.light !== "false"; - const failed = process.env.failed; - const keepFailed = process.env.keepFailed || failed; - const stackTraceLimit = process.env.stackTraceLimit; - const colorsFlag = process.env.color || process.env.colors; - const colors = colorsFlag !== "false" && colorsFlag !== "0"; - const reporter = process.env.reporter || process.env.r || defaultReporter; - const bail = process.env.bail || process.env.b; - const lintFlag = process.env.lint !== 'false'; - const testConfigFile = 'test.config'; - - if (fs.existsSync(testConfigFile)) { - fs.unlinkSync(testConfigFile); - } - - let workerCount, taskConfigsFolder; - if (runInParallel) { - // generate name to store task configuration files - const prefix = os.tmpdir() + "/ts-tests"; - let i = 1; - do { - taskConfigsFolder = prefix + i; - i++; - } while (fs.existsSync(taskConfigsFolder)); - fs.mkdirSync(taskConfigsFolder); - - workerCount = process.env.workerCount || process.env.p || os.cpus().length; - } - - if (tests && tests.toLocaleLowerCase() === "rwc") { - testTimeout = 800000; - } - - if (tests || runners || light || testTimeout || taskConfigsFolder || keepFailed) { - writeTestConfigFile(tests, runners, light, taskConfigsFolder, workerCount, stackTraceLimit, colors, testTimeout, keepFailed); - } - - // timeout normally isn't necessary but Travis-CI has been timing out on compiler baselines occasionally - // default timeout is 2sec which really should be enough, but maybe we just need a small amount longer - if (!runInParallel) { - var startTime = Travis.mark(); - var args = []; - args.push("-R", "scripts/failed-tests"); - args.push("-O", '"reporter=' + reporter + (keepFailed ? ",keepFailed=true" : "") + '"'); - if (tests) args.push("-g", `"${tests}"`); - args.push(colors ? "--colors" : "--no-colors"); - if (bail) args.push("--bail"); - if (inspect) { - args.unshift("--inspect-brk"); - } else { - args.push("-t", testTimeout); - } - args.push(Paths.builtLocalRun); - - var cmd; - if (failed) { - args.unshift("scripts/run-failed-tests.js"); - cmd = host + " " + args.join(" "); - } - else { - cmd = "mocha " + args.join(" "); - } - var savedNodeEnv = process.env.NODE_ENV; - process.env.NODE_ENV = "development"; - exec(cmd, function () { - process.env.NODE_ENV = savedNodeEnv; - Travis.measure(startTime); - runLinterAndComplete(); - }, function (e, status) { - process.env.NODE_ENV = savedNodeEnv; - Travis.measure(startTime); - finish(status); - }); - } - else { - var savedNodeEnv = process.env.NODE_ENV; - process.env.NODE_ENV = "development"; - var startTime = Travis.mark(); - const cmd = `${host} ${Paths.builtLocalRun}`; - exec(cmd, function () { - // Tests succeeded; run 'lint' task - process.env.NODE_ENV = savedNodeEnv; - Travis.measure(startTime); - runLinterAndComplete(); - }, function (e, status) { - // Tests failed - process.env.NODE_ENV = savedNodeEnv; - Travis.measure(startTime); - finish(status); - }); - } - - function finish(errorStatus) { - deleteTemporaryProjectOutput(); - if (errorStatus !== undefined) { - fail("Process exited with code " + errorStatus); - } - else { - complete(); - } - } - - function runLinterAndComplete() { - if (!lintFlag || dirty) { - return finish(); - } - var lint = jake.Task['lint']; - lint.once('complete', function () { - finish(); - }); - lint.invoke(); - } - - function deleteTemporaryProjectOutput() { - if (fs.existsSync(path.join(Paths.baselines.local, "projectOutput/"))) { - jake.rmRf(path.join(Paths.baselines.local, "projectOutput/")); - } - } -} - -// used to pass data from jake command line directly to run.js -function writeTestConfigFile(tests, runners, light, taskConfigsFolder, workerCount, stackTraceLimit, colors, testTimeout, keepFailed) { - var testConfigContents = JSON.stringify({ - runners: runners ? runners.split(",") : undefined, - test: tests ? [tests] : undefined, - light: light, - workerCount: workerCount, - taskConfigsFolder: taskConfigsFolder, - stackTraceLimit: stackTraceLimit, - noColor: !colors, - timeout: testTimeout, - keepFailed: keepFailed - }); - fs.writeFileSync('test.config', testConfigContents, { encoding: "utf-8" }); -} - -function cleanTestDirs() { - // Clean the local baselines directory - if (fs.existsSync(Paths.baselines.local)) { - del.sync(Paths.baselines.local); - } - - // Clean the local Rwc baselines directory - if (fs.existsSync(Paths.baselines.localRwc)) { - del.sync(Paths.baselines.localRwc); - } - - jake.mkdirP(Paths.baselines.local); - jake.mkdirP(Paths.baselines.localTest262); -} - -function tsbuild(tsconfigPath, useLkg = true, done = undefined) { - const startCompileTime = Travis.mark(); - const compilerPath = useLkg ? Paths.lkgCompiler : Paths.builtLocalCompiler; - const cmd = `${host} ${compilerPath} -b ${Array.isArray(tsconfigPath) ? tsconfigPath.join(" ") : tsconfigPath}`; - - exec(cmd, () => { - // Success - Travis.measure(startCompileTime); - done ? done() : complete(); - }, () => { - // Fail - Travis.measure(startCompileTime); - fail(`Compilation of ${tsconfigPath} unsuccessful`); - }); -} - -const Travis = { - mark() { - if (!fold.isTravis()) return; - var stamp = process.hrtime(); - var id = Math.floor(Math.random() * 0xFFFFFFFF).toString(16); - console.log("travis_time:start:" + id + "\r"); - return { - stamp: stamp, - id: id - }; - }, - measure(marker) { - if (!fold.isTravis()) return; - var diff = process.hrtime(marker.stamp); - var total = [marker.stamp[0] + diff[0], marker.stamp[1] + diff[1]]; - console.log("travis_time:end:" + marker.id + ":start=" + toNs(marker.stamp) + ",finish=" + toNs(total) + ",duration=" + toNs(diff) + "\r"); - } -}; - -function toNs(diff) { - return diff[0] * 1e9 + diff[1]; -} - -function exec(cmd, successHandler, errorHandler) { - var ex = jake.createExec([cmd], /** @type {jake.ExecOptions} */({ windowsVerbatimArguments: true, interactive: true })); - // Add listeners for output and error - ex.addListener("stdout", function (output) { - process.stdout.write(output); - }); - ex.addListener("stderr", function (error) { - process.stderr.write(error); - }); - ex.addListener("cmdEnd", function () { - if (successHandler) { - successHandler(); - } - }); - ex.addListener("error", function (e, status) { - if (errorHandler) { - errorHandler(e, status); - } - else { - fail("Process exited with code " + status); - } - }); - - console.log(cmd); - ex.run(); -} - -function acceptBaseline(sourceFolder, targetFolder) { - console.log('Accept baselines from ' + sourceFolder + ' to ' + targetFolder); - var deleteEnding = '.delete'; - - jake.mkdirP(targetFolder); - acceptBaselineFolder(sourceFolder, targetFolder); - - function acceptBaselineFolder(sourceFolder, targetFolder) { - var files = fs.readdirSync(sourceFolder); - - for (var i in files) { - var filename = files[i]; - var fullLocalPath = path.join(sourceFolder, filename); - var stat = fs.statSync(fullLocalPath); - if (stat.isFile()) { - if (filename.substr(filename.length - deleteEnding.length) === deleteEnding) { - filename = filename.substr(0, filename.length - deleteEnding.length); - fs.unlinkSync(path.join(targetFolder, filename)); - } - else { - var target = path.join(targetFolder, filename); - if (fs.existsSync(target)) { - fs.unlinkSync(target); - } - jake.mkdirP(path.dirname(target)); - fs.renameSync(path.join(sourceFolder, filename), target); - } - } - else if (stat.isDirectory()) { - acceptBaselineFolder(fullLocalPath, path.join(targetFolder, filename)); - } - } - } -} - -/** @param jsonPath {string} */ -function readJson(jsonPath) { - const jsonText = readFileSync(jsonPath); - const result = ts.parseConfigFileTextToJson(jsonPath, jsonText); - if (result.error) { - reportDiagnostics([result.error]); - throw new Error("An error occurred during parse."); - } - return result.config; -} - -/** @param diagnostics {ts.Diagnostic[]} */ -function reportDiagnostics(diagnostics) { - console.log(diagnosticsToString(diagnostics, process.stdout.isTTY)); -} - -/** - * @param diagnostics {ts.Diagnostic[]} - * @param [pretty] {boolean} - */ -function diagnosticsToString(diagnostics, pretty) { - const host = { - getCurrentDirectory() { return process.cwd(); }, - getCanonicalFileName(fileName) { return fileName; }, - getNewLine() { return os.EOL; } - }; - return pretty ? ts.formatDiagnosticsWithColorAndContext(diagnostics, host) : - ts.formatDiagnostics(diagnostics, host); -} - -/** - * Concatenate a list of sourceFiles to a destinationFile - * @param {string} destinationFile - * @param {string[]} sourceFiles - * @param {string=} extraContent - */ -function concatenateFiles(destinationFile, sourceFiles, extraContent) { - var temp = "temptemp"; - // append all files in sequence - var text = ""; - for (var i = 0; i < sourceFiles.length; i++) { - if (!fs.existsSync(sourceFiles[i])) { - fail(sourceFiles[i] + " does not exist!"); - } - if (i > 0) { text += "\n\n"; } - text += readFileSync(sourceFiles[i]).replace(/\r?\n/g, "\n"); - } - if (extraContent) { - text += extraContent; - } - fs.writeFileSync(temp, text); - // Move the file to the final destination - fs.renameSync(temp, destinationFile); -} - -function appendToFile(path, content) { - fs.writeFileSync(path, readFileSync(path) + "\r\n" + content); -} - -/** - * - * @param {string} path - * @returns string - */ -function readFileSync(path) { - return fs.readFileSync(path, { encoding: "utf-8" }); -} - -function getDiffTool() { - var program = process.env['DIFF']; - if (!program) { - fail("Add the 'DIFF' environment variable to the path of the program you want to use."); - } - return program; -} - -/** - * Replaces const enum declarations with non-const enums - * @param {string} text - */ -function removeConstModifierFromEnumDeclarations(text) { - return text.replace(/^(\s*)(export )?const enum (\S+) {(\s*)$/gm, '$1$2enum $3 {$4'); -} \ No newline at end of file diff --git a/README.md b/README.md index 2826db8aec6..3b20af2d398 100644 --- a/README.md +++ b/README.md @@ -61,29 +61,29 @@ Change to the TypeScript directory: cd TypeScript ``` -Install [Jake](http://jakejs.com/) tools and dev dependencies: +Install [Gulp](https://gulpjs.com/) tools and dev dependencies: ```bash -npm install -g jake +npm install -g gulp npm install ``` Use one of the following to build and test: ``` -jake local # Build the compiler into built/local -jake clean # Delete the built compiler -jake LKG # Replace the last known good with the built one. +gulp local # Build the compiler into built/local +gulp clean # Delete the built compiler +gulp LKG # Replace the last known good with the built one. # Bootstrapping step to be executed when the built compiler reaches a stable state. -jake tests # Build the test infrastructure using the built compiler. -jake runtests # Run tests using the built compiler and test infrastructure. +gulp tests # Build the test infrastructure using the built compiler. +gulp runtests # Run tests using the built compiler and test infrastructure. # You can override the host or specify a test for this command. - # Use host= or tests=. -jake runtests-browser # Runs the tests using the built run.js file. Syntax is jake runtests. Optional - parameters 'host=', 'tests=[regex], reporter=[list|spec|json|]'. -jake baseline-accept # This replaces the baseline test results with the results obtained from jake runtests. -jake lint # Runs tslint on the TypeScript source. -jake help # List the above commands. + # Use --host= or --tests=. +gulp runtests-browser # Runs the tests using the built run.js file. Syntax is gulp runtests. Optional + parameters '--host=', '--tests=[regex], --reporter=[list|spec|json|]'. +gulp baseline-accept # This replaces the baseline test results with the results obtained from gulp runtests. +gulp lint # Runs tslint on the TypeScript source. +gulp help # List the above commands. ``` diff --git a/lib/README.md b/lib/README.md index 0a85a9e7b5c..ce0455fa40d 100644 --- a/lib/README.md +++ b/lib/README.md @@ -2,4 +2,4 @@ **These files are not meant to be edited by hand.** If you need to make modifications, the respective files should be changed within the repository's top-level `src` directory. -Running `jake LKG` will then appropriately update the files in this directory. +Running `gulp LKG` will then appropriately update the files in this directory. diff --git a/package.json b/package.json index abf7aa17d35..275411c477f 100644 --- a/package.json +++ b/package.json @@ -68,7 +68,6 @@ "gulp-rename": "latest", "gulp-sourcemaps": "latest", "istanbul": "latest", - "jake": "latest", "lodash": "^4.17.11", "merge2": "latest", "minimist": "latest", @@ -91,16 +90,16 @@ "xml2js": "^0.4.19" }, "scripts": { - "pretest": "jake tests", - "test": "jake runtests-parallel light=false", + "pretest": "gulp tests", + "test": "gulp runtests-parallel --light=false", "build": "npm run build:compiler && npm run build:tests", - "build:compiler": "jake local", - "build:tests": "jake tests", + "build:compiler": "gulp local", + "build:tests": "gulp tests", "start": "node lib/tsc", - "clean": "jake clean", + "clean": "gulp clean", "gulp": "gulp", - "jake": "jake", - "lint": "jake lint", + "jake": "gulp", + "lint": "gulp lint", "setup-hooks": "node scripts/link-hooks.js" }, "browser": { diff --git a/scripts/bisect-test.ts b/scripts/bisect-test.ts index cc0248f6d64..d66e0b71061 100644 --- a/scripts/bisect-test.ts +++ b/scripts/bisect-test.ts @@ -15,6 +15,7 @@ function tsc(tscArgs: string, onExit: (exitCode: number) => void) { }); } +// TODO: Rewrite bisect script to handle the post-jake/gulp swap period var jake = cp.exec('jake clean local', () => void 0); jake.on('close', jakeExitCode => { if (jakeExitCode === 0) { diff --git a/scripts/build/tests.js b/scripts/build/tests.js index 36a9ea54cb9..bcf5431b8d9 100644 --- a/scripts/build/tests.js +++ b/scripts/build/tests.js @@ -116,6 +116,17 @@ async function runConsoleTests(runJs, defaultReporter, runInParallel, watchMode, errorStatus = exitCode; error = new Error(`Process exited with status code ${errorStatus}.`); } + else if (process.env.CI === "true") { + // finally, do a sanity check and build the compiler with the built version of itself + log.info("Starting sanity check build..."); + // Cleanup everything except lint rules (we'll need those later and would rather not waste time rebuilding them) + await exec("gulp", ["clean-tsc", "clean-services", "clean-tsserver", "clean-lssl", "clean-tests"], { cancelToken }); + const { exitCode } = await exec("gulp", ["local", "--lkg=false"], { cancelToken }); + if (exitCode !== 0) { + errorStatus = exitCode; + error = new Error(`Sanity check build process exited with status code ${errorStatus}.`); + } + } } catch (e) { errorStatus = undefined; @@ -148,7 +159,7 @@ async function cleanTestDirs() { exports.cleanTestDirs = cleanTestDirs; /** - * used to pass data from jake command line directly to run.js + * used to pass data from gulp command line directly to run.js * @param {string} tests * @param {string} runners * @param {boolean} light diff --git a/scripts/hooks/post-checkout b/scripts/hooks/post-checkout index fb41e4e8652..28a583794d9 100644 --- a/scripts/hooks/post-checkout +++ b/scripts/hooks/post-checkout @@ -1,2 +1,2 @@ #!/bin/sh -npm run jake -- generate-diagnostics \ No newline at end of file +npm run gulp -- generate-diagnostics \ No newline at end of file diff --git a/scripts/open-user-pr.ts b/scripts/open-user-pr.ts index f510c63d4e3..aedfcc42547 100644 --- a/scripts/open-user-pr.ts +++ b/scripts/open-user-pr.ts @@ -24,7 +24,7 @@ const branchName = `user-update-${now.getFullYear()}${padNum(now.getMonth())}${p const remoteUrl = `https://${process.argv[2]}@github.com/${userName}/TypeScript.git`; runSequence([ ["git", ["checkout", "."]], // reset any changes - ["node", ["./node_modules/jake/bin/cli.js", "baseline-accept"]], // accept baselines + ["node", ["./node_modules/gulp/bin/gulp.js", "baseline-accept"]], // accept baselines ["git", ["checkout", "-b", branchName]], // create a branch ["git", ["add", "."]], // Add all changes ["git", ["commit", "-m", `"Update user baselines"`]], // Commit all changes diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 70fccdf87c1..36c246c999f 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -8347,7 +8347,7 @@ declare namespace ts.server { excludedFiles: ReadonlyArray; private typeAcquisition; updateGraph(): boolean; - getExcludedFiles(): readonly NormalizedPath[]; + getExcludedFiles(): ReadonlyArray; getTypeAcquisition(): TypeAcquisition; setTypeAcquisition(newTypeAcquisition: TypeAcquisition): void; } From cee933ff099af026eba520cc34281765ea4a621a Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 21 Feb 2019 10:31:55 -0800 Subject: [PATCH 088/149] Be more specific in errors. --- src/compiler/checker.ts | 2 +- src/compiler/diagnosticMessages.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 9ac19fb98d0..53ded49daed 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -24448,7 +24448,7 @@ namespace ts { const bodySignature = getSignatureFromDeclaration(bodyDeclaration); for (const signature of signatures) { if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { - error(signature.declaration, Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); + error(signature.declaration, Diagnostics.This_overload_signature_is_not_compatible_with_its_implementation_signature); break; } } diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 89794d26181..c0686d10db6 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -1404,7 +1404,7 @@ "category": "Error", "code": 2393 }, - "Overload signature is not compatible with function implementation.": { + "This overload signature is not compatible with its implementation signature.": { "category": "Error", "code": 2394 }, From 4a256abc8a18335f55f8ce21abea9f25c471823f Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 21 Feb 2019 10:42:38 -0800 Subject: [PATCH 089/149] Give a related span pointing to the implementation signature when reporting incompatibility. --- src/compiler/checker.ts | 5 ++++- src/compiler/diagnosticMessages.json | 4 ++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 53ded49daed..958ceae0395 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -24448,7 +24448,10 @@ namespace ts { const bodySignature = getSignatureFromDeclaration(bodyDeclaration); for (const signature of signatures) { if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { - error(signature.declaration, Diagnostics.This_overload_signature_is_not_compatible_with_its_implementation_signature); + addRelatedInfo( + error(signature.declaration, Diagnostics.This_overload_signature_is_not_compatible_with_its_implementation_signature), + createDiagnosticForNode(bodyDeclaration, Diagnostics.The_implementation_signature_is_declared_here) + ); break; } } diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index c0686d10db6..09b0f721292 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -2585,6 +2585,10 @@ "category": "Error", "code": 2749 }, + "The implementation signature is declared here.": { + "category": "Error", + "code": 2750 + }, "Import declaration '{0}' is using private name '{1}'.": { "category": "Error", From d6bb3ee64cf3c51f0014c0f6410ab72df7803b25 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 21 Feb 2019 10:45:40 -0800 Subject: [PATCH 090/149] Accepted baselines. --- .../reference/anyIdenticalToItself.errors.txt | 5 +++-- ...nstructorsWithSpecializedSignatures.errors.txt | 10 ++++++---- ...ctionAndInterfaceWithSeparateErrors.errors.txt | 5 +++-- ...tionOverloadCompatibilityWithVoid01.errors.txt | 5 +++-- .../reference/functionOverloadErrors.errors.txt | 15 +++++++++------ .../reference/functionOverloads11.errors.txt | 5 +++-- .../reference/functionOverloads17.errors.txt | 5 +++-- .../reference/functionOverloads18.errors.txt | 5 +++-- .../reference/functionOverloads19.errors.txt | 5 +++-- .../reference/functionOverloads20.errors.txt | 5 +++-- .../reference/functionOverloads4.errors.txt | 5 +++-- .../reference/overloadAssignmentCompat.errors.txt | 5 +++-- .../overloadOnConstNoAnyImplementation.errors.txt | 5 +++-- ...overloadOnConstNoAnyImplementation2.errors.txt | 5 +++-- ...overloadOnConstantsInvalidOverload1.errors.txt | 5 +++-- .../reference/overloadingOnConstants2.errors.txt | 10 ++++++---- .../parameterPropertyInConstructor2.errors.txt | 5 +++-- .../reference/parserClassDeclaration12.errors.txt | 5 +++-- .../reference/parserParameterList15.errors.txt | 5 +++-- .../reference/parserParameterList16.errors.txt | 5 +++-- .../reference/parserParameterList17.errors.txt | 5 +++-- .../reference/recursiveFunctionTypes.errors.txt | 5 +++-- ...NotSubtypeOfNonSpecializedSignature.errors.txt | 5 +++-- .../stringLiteralTypesOverloads05.errors.txt | 5 +++-- ...mplateStringInFunctionParameterType.errors.txt | 5 +++-- ...ateStringInFunctionParameterTypeES6.errors.txt | 5 +++-- .../voidAsNonAmbiguousReturnType.errors.txt | 5 +++-- 27 files changed, 93 insertions(+), 62 deletions(-) diff --git a/tests/baselines/reference/anyIdenticalToItself.errors.txt b/tests/baselines/reference/anyIdenticalToItself.errors.txt index bcd3b52daef..3eff1c4b87a 100644 --- a/tests/baselines/reference/anyIdenticalToItself.errors.txt +++ b/tests/baselines/reference/anyIdenticalToItself.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/anyIdenticalToItself.ts(1,10): error TS2394: Overload signature is not compatible with function implementation. +tests/cases/compiler/anyIdenticalToItself.ts(1,10): error TS2394: This overload signature is not compatible with its implementation signature. tests/cases/compiler/anyIdenticalToItself.ts(6,9): error TS1056: Accessors are only available when targeting ECMAScript 5 and higher. tests/cases/compiler/anyIdenticalToItself.ts(10,9): error TS1056: Accessors are only available when targeting ECMAScript 5 and higher. @@ -6,7 +6,8 @@ tests/cases/compiler/anyIdenticalToItself.ts(10,9): error TS1056: Accessors are ==== tests/cases/compiler/anyIdenticalToItself.ts (3 errors) ==== function foo(x: any); ~~~ -!!! error TS2394: Overload signature is not compatible with function implementation. +!!! error TS2394: This overload signature is not compatible with its implementation signature. +!!! related TS2750 tests/cases/compiler/anyIdenticalToItself.ts:3:10: The implementation signature is declared here. function foo(x: any); function foo(x: any, y: number) { } diff --git a/tests/baselines/reference/constructorsWithSpecializedSignatures.errors.txt b/tests/baselines/reference/constructorsWithSpecializedSignatures.errors.txt index 4f869fd63a0..682959074e8 100644 --- a/tests/baselines/reference/constructorsWithSpecializedSignatures.errors.txt +++ b/tests/baselines/reference/constructorsWithSpecializedSignatures.errors.txt @@ -1,5 +1,5 @@ -tests/cases/compiler/constructorsWithSpecializedSignatures.ts(18,5): error TS2394: Overload signature is not compatible with function implementation. -tests/cases/compiler/constructorsWithSpecializedSignatures.ts(26,5): error TS2394: Overload signature is not compatible with function implementation. +tests/cases/compiler/constructorsWithSpecializedSignatures.ts(18,5): error TS2394: This overload signature is not compatible with its implementation signature. +tests/cases/compiler/constructorsWithSpecializedSignatures.ts(26,5): error TS2394: This overload signature is not compatible with its implementation signature. ==== tests/cases/compiler/constructorsWithSpecializedSignatures.ts (2 errors) ==== @@ -22,7 +22,8 @@ tests/cases/compiler/constructorsWithSpecializedSignatures.ts(26,5): error TS239 constructor(x: "hi"); constructor(x: "foo"); ~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2394: Overload signature is not compatible with function implementation. +!!! error TS2394: This overload signature is not compatible with its implementation signature. +!!! related TS2750 tests/cases/compiler/constructorsWithSpecializedSignatures.ts:20:5: The implementation signature is declared here. constructor(x: number); constructor(x: "hi") { } } @@ -32,7 +33,8 @@ tests/cases/compiler/constructorsWithSpecializedSignatures.ts(26,5): error TS239 constructor(x: "hi"); constructor(x: "foo"); ~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2394: Overload signature is not compatible with function implementation. +!!! error TS2394: This overload signature is not compatible with its implementation signature. +!!! related TS2750 tests/cases/compiler/constructorsWithSpecializedSignatures.ts:28:5: The implementation signature is declared here. constructor(x: string); constructor(x: "hi") { } // error } diff --git a/tests/baselines/reference/functionAndInterfaceWithSeparateErrors.errors.txt b/tests/baselines/reference/functionAndInterfaceWithSeparateErrors.errors.txt index a87dc989178..a22bdef2199 100644 --- a/tests/baselines/reference/functionAndInterfaceWithSeparateErrors.errors.txt +++ b/tests/baselines/reference/functionAndInterfaceWithSeparateErrors.errors.txt @@ -1,11 +1,12 @@ -tests/cases/compiler/functionAndInterfaceWithSeparateErrors.ts(1,10): error TS2394: Overload signature is not compatible with function implementation. +tests/cases/compiler/functionAndInterfaceWithSeparateErrors.ts(1,10): error TS2394: This overload signature is not compatible with its implementation signature. tests/cases/compiler/functionAndInterfaceWithSeparateErrors.ts(6,5): error TS2411: Property 'prop' of type 'number' is not assignable to string index type 'string'. ==== tests/cases/compiler/functionAndInterfaceWithSeparateErrors.ts (2 errors) ==== function Foo(s: string); ~~~ -!!! error TS2394: Overload signature is not compatible with function implementation. +!!! error TS2394: This overload signature is not compatible with its implementation signature. +!!! related TS2750 tests/cases/compiler/functionAndInterfaceWithSeparateErrors.ts:2:10: The implementation signature is declared here. function Foo(n: number) { } interface Foo { diff --git a/tests/baselines/reference/functionOverloadCompatibilityWithVoid01.errors.txt b/tests/baselines/reference/functionOverloadCompatibilityWithVoid01.errors.txt index 56951e380e4..5e81224b5eb 100644 --- a/tests/baselines/reference/functionOverloadCompatibilityWithVoid01.errors.txt +++ b/tests/baselines/reference/functionOverloadCompatibilityWithVoid01.errors.txt @@ -1,10 +1,11 @@ -tests/cases/conformance/functions/functionOverloadCompatibilityWithVoid01.ts(1,10): error TS2394: Overload signature is not compatible with function implementation. +tests/cases/conformance/functions/functionOverloadCompatibilityWithVoid01.ts(1,10): error TS2394: This overload signature is not compatible with its implementation signature. ==== tests/cases/conformance/functions/functionOverloadCompatibilityWithVoid01.ts (1 errors) ==== function f(x: string): number; ~ -!!! error TS2394: Overload signature is not compatible with function implementation. +!!! error TS2394: This overload signature is not compatible with its implementation signature. +!!! related TS2750 tests/cases/conformance/functions/functionOverloadCompatibilityWithVoid01.ts:2:10: The implementation signature is declared here. function f(x: string): void { return; } \ No newline at end of file diff --git a/tests/baselines/reference/functionOverloadErrors.errors.txt b/tests/baselines/reference/functionOverloadErrors.errors.txt index ddcaf478602..66f0751fb42 100644 --- a/tests/baselines/reference/functionOverloadErrors.errors.txt +++ b/tests/baselines/reference/functionOverloadErrors.errors.txt @@ -5,9 +5,9 @@ tests/cases/conformance/functions/functionOverloadErrors.ts(75,21): error TS2383 tests/cases/conformance/functions/functionOverloadErrors.ts(79,14): error TS2383: Overload signatures must all be exported or non-exported. tests/cases/conformance/functions/functionOverloadErrors.ts(85,18): error TS2384: Overload signatures must all be ambient or non-ambient. tests/cases/conformance/functions/functionOverloadErrors.ts(90,18): error TS2384: Overload signatures must all be ambient or non-ambient. -tests/cases/conformance/functions/functionOverloadErrors.ts(94,10): error TS2394: Overload signature is not compatible with function implementation. -tests/cases/conformance/functions/functionOverloadErrors.ts(99,10): error TS2394: Overload signature is not compatible with function implementation. -tests/cases/conformance/functions/functionOverloadErrors.ts(103,10): error TS2394: Overload signature is not compatible with function implementation. +tests/cases/conformance/functions/functionOverloadErrors.ts(94,10): error TS2394: This overload signature is not compatible with its implementation signature. +tests/cases/conformance/functions/functionOverloadErrors.ts(99,10): error TS2394: This overload signature is not compatible with its implementation signature. +tests/cases/conformance/functions/functionOverloadErrors.ts(103,10): error TS2394: This overload signature is not compatible with its implementation signature. tests/cases/conformance/functions/functionOverloadErrors.ts(116,19): error TS2371: A parameter initializer is only allowed in a function or constructor implementation. @@ -121,20 +121,23 @@ tests/cases/conformance/functions/functionOverloadErrors.ts(116,19): error TS237 //Function overloads with fewer params than implementation signature function fewerParams(); ~~~~~~~~~~~ -!!! error TS2394: Overload signature is not compatible with function implementation. +!!! error TS2394: This overload signature is not compatible with its implementation signature. +!!! related TS2750 tests/cases/conformance/functions/functionOverloadErrors.ts:95:10: The implementation signature is declared here. function fewerParams(n: string) { } //Function implementation whose parameter types are not assignable to all corresponding overload signature parameters function fn13(n: string); ~~~~ -!!! error TS2394: Overload signature is not compatible with function implementation. +!!! error TS2394: This overload signature is not compatible with its implementation signature. +!!! related TS2750 tests/cases/conformance/functions/functionOverloadErrors.ts:100:10: The implementation signature is declared here. function fn13(n: number) { } //Function overloads where return types are not all subtype of implementation return type function fn14(n: string): string; ~~~~ -!!! error TS2394: Overload signature is not compatible with function implementation. +!!! error TS2394: This overload signature is not compatible with its implementation signature. +!!! related TS2750 tests/cases/conformance/functions/functionOverloadErrors.ts:104:10: The implementation signature is declared here. function fn14() { return 3; } diff --git a/tests/baselines/reference/functionOverloads11.errors.txt b/tests/baselines/reference/functionOverloads11.errors.txt index 005ee9bb143..a2e37789b60 100644 --- a/tests/baselines/reference/functionOverloads11.errors.txt +++ b/tests/baselines/reference/functionOverloads11.errors.txt @@ -1,9 +1,10 @@ -tests/cases/compiler/functionOverloads11.ts(1,10): error TS2394: Overload signature is not compatible with function implementation. +tests/cases/compiler/functionOverloads11.ts(1,10): error TS2394: This overload signature is not compatible with its implementation signature. ==== tests/cases/compiler/functionOverloads11.ts (1 errors) ==== function foo():number; ~~~ -!!! error TS2394: Overload signature is not compatible with function implementation. +!!! error TS2394: This overload signature is not compatible with its implementation signature. +!!! related TS2750 tests/cases/compiler/functionOverloads11.ts:2:10: The implementation signature is declared here. function foo():string { return "" } \ No newline at end of file diff --git a/tests/baselines/reference/functionOverloads17.errors.txt b/tests/baselines/reference/functionOverloads17.errors.txt index febd2c03ac8..1945e3fc17a 100644 --- a/tests/baselines/reference/functionOverloads17.errors.txt +++ b/tests/baselines/reference/functionOverloads17.errors.txt @@ -1,9 +1,10 @@ -tests/cases/compiler/functionOverloads17.ts(1,10): error TS2394: Overload signature is not compatible with function implementation. +tests/cases/compiler/functionOverloads17.ts(1,10): error TS2394: This overload signature is not compatible with its implementation signature. ==== tests/cases/compiler/functionOverloads17.ts (1 errors) ==== function foo():{a:number;} ~~~ -!!! error TS2394: Overload signature is not compatible with function implementation. +!!! error TS2394: This overload signature is not compatible with its implementation signature. +!!! related TS2750 tests/cases/compiler/functionOverloads17.ts:2:10: The implementation signature is declared here. function foo():{a:string;} { return {a:""} } \ No newline at end of file diff --git a/tests/baselines/reference/functionOverloads18.errors.txt b/tests/baselines/reference/functionOverloads18.errors.txt index bec6a45ed89..6010c633abf 100644 --- a/tests/baselines/reference/functionOverloads18.errors.txt +++ b/tests/baselines/reference/functionOverloads18.errors.txt @@ -1,9 +1,10 @@ -tests/cases/compiler/functionOverloads18.ts(1,10): error TS2394: Overload signature is not compatible with function implementation. +tests/cases/compiler/functionOverloads18.ts(1,10): error TS2394: This overload signature is not compatible with its implementation signature. ==== tests/cases/compiler/functionOverloads18.ts (1 errors) ==== function foo(bar:{a:number;}); ~~~ -!!! error TS2394: Overload signature is not compatible with function implementation. +!!! error TS2394: This overload signature is not compatible with its implementation signature. +!!! related TS2750 tests/cases/compiler/functionOverloads18.ts:2:10: The implementation signature is declared here. function foo(bar:{a:string;}) { return {a:""} } \ No newline at end of file diff --git a/tests/baselines/reference/functionOverloads19.errors.txt b/tests/baselines/reference/functionOverloads19.errors.txt index d87ba17562a..bd2ce38ec16 100644 --- a/tests/baselines/reference/functionOverloads19.errors.txt +++ b/tests/baselines/reference/functionOverloads19.errors.txt @@ -1,10 +1,11 @@ -tests/cases/compiler/functionOverloads19.ts(1,10): error TS2394: Overload signature is not compatible with function implementation. +tests/cases/compiler/functionOverloads19.ts(1,10): error TS2394: This overload signature is not compatible with its implementation signature. ==== tests/cases/compiler/functionOverloads19.ts (1 errors) ==== function foo(bar:{b:string;}); ~~~ -!!! error TS2394: Overload signature is not compatible with function implementation. +!!! error TS2394: This overload signature is not compatible with its implementation signature. +!!! related TS2750 tests/cases/compiler/functionOverloads19.ts:3:10: The implementation signature is declared here. function foo(bar:{a:string;}); function foo(bar:{a:any;}) { return {a:""} } \ No newline at end of file diff --git a/tests/baselines/reference/functionOverloads20.errors.txt b/tests/baselines/reference/functionOverloads20.errors.txt index 6b33795bc3e..b4e4f969dfb 100644 --- a/tests/baselines/reference/functionOverloads20.errors.txt +++ b/tests/baselines/reference/functionOverloads20.errors.txt @@ -1,10 +1,11 @@ -tests/cases/compiler/functionOverloads20.ts(1,10): error TS2394: Overload signature is not compatible with function implementation. +tests/cases/compiler/functionOverloads20.ts(1,10): error TS2394: This overload signature is not compatible with its implementation signature. ==== tests/cases/compiler/functionOverloads20.ts (1 errors) ==== function foo(bar:{a:number;}): number; ~~~ -!!! error TS2394: Overload signature is not compatible with function implementation. +!!! error TS2394: This overload signature is not compatible with its implementation signature. +!!! related TS2750 tests/cases/compiler/functionOverloads20.ts:3:10: The implementation signature is declared here. function foo(bar:{a:string;}): string; function foo(bar:{a:any;}): string {return ""} \ No newline at end of file diff --git a/tests/baselines/reference/functionOverloads4.errors.txt b/tests/baselines/reference/functionOverloads4.errors.txt index 78d772a0f6f..d9ce3a7d189 100644 --- a/tests/baselines/reference/functionOverloads4.errors.txt +++ b/tests/baselines/reference/functionOverloads4.errors.txt @@ -1,8 +1,9 @@ -tests/cases/compiler/functionOverloads4.ts(1,10): error TS2394: Overload signature is not compatible with function implementation. +tests/cases/compiler/functionOverloads4.ts(1,10): error TS2394: This overload signature is not compatible with its implementation signature. ==== tests/cases/compiler/functionOverloads4.ts (1 errors) ==== function foo():number; ~~~ -!!! error TS2394: Overload signature is not compatible with function implementation. +!!! error TS2394: This overload signature is not compatible with its implementation signature. +!!! related TS2750 tests/cases/compiler/functionOverloads4.ts:2:10: The implementation signature is declared here. function foo():string { return "a" } \ No newline at end of file diff --git a/tests/baselines/reference/overloadAssignmentCompat.errors.txt b/tests/baselines/reference/overloadAssignmentCompat.errors.txt index 35906ee92c9..a0609b70e71 100644 --- a/tests/baselines/reference/overloadAssignmentCompat.errors.txt +++ b/tests/baselines/reference/overloadAssignmentCompat.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/overloadAssignmentCompat.ts(34,10): error TS2394: Overload signature is not compatible with function implementation. +tests/cases/compiler/overloadAssignmentCompat.ts(34,10): error TS2394: This overload signature is not compatible with its implementation signature. ==== tests/cases/compiler/overloadAssignmentCompat.ts (1 errors) ==== @@ -37,7 +37,8 @@ tests/cases/compiler/overloadAssignmentCompat.ts(34,10): error TS2394: Overload // error - signatures are not assignment compatible function foo():number; ~~~ -!!! error TS2394: Overload signature is not compatible with function implementation. +!!! error TS2394: This overload signature is not compatible with its implementation signature. +!!! related TS2750 tests/cases/compiler/overloadAssignmentCompat.ts:35:10: The implementation signature is declared here. function foo():string { return "a" }; \ No newline at end of file diff --git a/tests/baselines/reference/overloadOnConstNoAnyImplementation.errors.txt b/tests/baselines/reference/overloadOnConstNoAnyImplementation.errors.txt index aa7bbf77239..457f7f5b388 100644 --- a/tests/baselines/reference/overloadOnConstNoAnyImplementation.errors.txt +++ b/tests/baselines/reference/overloadOnConstNoAnyImplementation.errors.txt @@ -1,11 +1,12 @@ -tests/cases/compiler/overloadOnConstNoAnyImplementation.ts(1,10): error TS2394: Overload signature is not compatible with function implementation. +tests/cases/compiler/overloadOnConstNoAnyImplementation.ts(1,10): error TS2394: This overload signature is not compatible with its implementation signature. tests/cases/compiler/overloadOnConstNoAnyImplementation.ts(9,8): error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. ==== tests/cases/compiler/overloadOnConstNoAnyImplementation.ts (2 errors) ==== function x1(a: number, cb: (x: 'hi') => number); ~~ -!!! error TS2394: Overload signature is not compatible with function implementation. +!!! error TS2394: This overload signature is not compatible with its implementation signature. +!!! related TS2750 tests/cases/compiler/overloadOnConstNoAnyImplementation.ts:3:10: The implementation signature is declared here. function x1(a: number, cb: (x: 'bye') => number); function x1(a: number, cb: (x: string) => number) { cb('hi'); diff --git a/tests/baselines/reference/overloadOnConstNoAnyImplementation2.errors.txt b/tests/baselines/reference/overloadOnConstNoAnyImplementation2.errors.txt index a090f370863..f6792949e59 100644 --- a/tests/baselines/reference/overloadOnConstNoAnyImplementation2.errors.txt +++ b/tests/baselines/reference/overloadOnConstNoAnyImplementation2.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/overloadOnConstNoAnyImplementation2.ts(6,5): error TS2394: Overload signature is not compatible with function implementation. +tests/cases/compiler/overloadOnConstNoAnyImplementation2.ts(6,5): error TS2394: This overload signature is not compatible with its implementation signature. tests/cases/compiler/overloadOnConstNoAnyImplementation2.ts(12,18): error TS2345: Argument of type '1' is not assignable to parameter of type 'string'. tests/cases/compiler/overloadOnConstNoAnyImplementation2.ts(18,9): error TS2345: Argument of type '(x: "bye") => number' is not assignable to parameter of type '(x: "hi") => number'. Types of parameters 'x' and 'x' are incompatible. @@ -16,7 +16,8 @@ tests/cases/compiler/overloadOnConstNoAnyImplementation2.ts(21,9): error TS2345: class C { x1(a: number, callback: (x: 'hi') => number); ~~ -!!! error TS2394: Overload signature is not compatible with function implementation. +!!! error TS2394: This overload signature is not compatible with its implementation signature. +!!! related TS2750 tests/cases/compiler/overloadOnConstNoAnyImplementation2.ts:7:5: The implementation signature is declared here. x1(a: number, callback: (x: string) => number) { callback('hi'); callback('bye'); diff --git a/tests/baselines/reference/overloadOnConstantsInvalidOverload1.errors.txt b/tests/baselines/reference/overloadOnConstantsInvalidOverload1.errors.txt index 3fe0a43d855..9fc6c97f6b7 100644 --- a/tests/baselines/reference/overloadOnConstantsInvalidOverload1.errors.txt +++ b/tests/baselines/reference/overloadOnConstantsInvalidOverload1.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/overloadOnConstantsInvalidOverload1.ts(6,10): error TS2394: Overload signature is not compatible with function implementation. +tests/cases/compiler/overloadOnConstantsInvalidOverload1.ts(6,10): error TS2394: This overload signature is not compatible with its implementation signature. tests/cases/compiler/overloadOnConstantsInvalidOverload1.ts(11,5): error TS2345: Argument of type '"HI"' is not assignable to parameter of type '"SPAN"'. @@ -10,7 +10,8 @@ tests/cases/compiler/overloadOnConstantsInvalidOverload1.ts(11,5): error TS2345: function foo(name: "SPAN"): Derived1; ~~~ -!!! error TS2394: Overload signature is not compatible with function implementation. +!!! error TS2394: This overload signature is not compatible with its implementation signature. +!!! related TS2750 tests/cases/compiler/overloadOnConstantsInvalidOverload1.ts:7:10: The implementation signature is declared here. function foo(name: "DIV"): Derived2 { return null; } diff --git a/tests/baselines/reference/overloadingOnConstants2.errors.txt b/tests/baselines/reference/overloadingOnConstants2.errors.txt index f50a6bbd8c3..c12d77714a3 100644 --- a/tests/baselines/reference/overloadingOnConstants2.errors.txt +++ b/tests/baselines/reference/overloadingOnConstants2.errors.txt @@ -1,6 +1,6 @@ -tests/cases/compiler/overloadingOnConstants2.ts(9,10): error TS2394: Overload signature is not compatible with function implementation. +tests/cases/compiler/overloadingOnConstants2.ts(9,10): error TS2394: This overload signature is not compatible with its implementation signature. tests/cases/compiler/overloadingOnConstants2.ts(15,13): error TS2345: Argument of type '"um"' is not assignable to parameter of type '"bye"'. -tests/cases/compiler/overloadingOnConstants2.ts(19,10): error TS2394: Overload signature is not compatible with function implementation. +tests/cases/compiler/overloadingOnConstants2.ts(19,10): error TS2394: This overload signature is not compatible with its implementation signature. ==== tests/cases/compiler/overloadingOnConstants2.ts (3 errors) ==== @@ -14,7 +14,8 @@ tests/cases/compiler/overloadingOnConstants2.ts(19,10): error TS2394: Overload s function foo(x: "hi", items: string[]): D; function foo(x: "bye", items: string[]): E; ~~~ -!!! error TS2394: Overload signature is not compatible with function implementation. +!!! error TS2394: This overload signature is not compatible with its implementation signature. +!!! related TS2750 tests/cases/compiler/overloadingOnConstants2.ts:10:10: The implementation signature is declared here. function foo(x: string, items: string[]): C { return null; } @@ -28,7 +29,8 @@ tests/cases/compiler/overloadingOnConstants2.ts(19,10): error TS2394: Overload s //function bar(x: "hi", items: string[]): D; function bar(x: "bye", items: string[]): E; ~~~ -!!! error TS2394: Overload signature is not compatible with function implementation. +!!! error TS2394: This overload signature is not compatible with its implementation signature. +!!! related TS2750 tests/cases/compiler/overloadingOnConstants2.ts:21:10: The implementation signature is declared here. function bar(x: string, items: string[]): C; function bar(x: string, items: string[]): C { return null; diff --git a/tests/baselines/reference/parameterPropertyInConstructor2.errors.txt b/tests/baselines/reference/parameterPropertyInConstructor2.errors.txt index d1a0513c1f6..6f64fdc8669 100644 --- a/tests/baselines/reference/parameterPropertyInConstructor2.errors.txt +++ b/tests/baselines/reference/parameterPropertyInConstructor2.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/parameterPropertyInConstructor2.ts(3,5): error TS2394: Overload signature is not compatible with function implementation. +tests/cases/compiler/parameterPropertyInConstructor2.ts(3,5): error TS2394: This overload signature is not compatible with its implementation signature. tests/cases/compiler/parameterPropertyInConstructor2.ts(3,17): error TS2369: A parameter property is only allowed in a constructor implementation. tests/cases/compiler/parameterPropertyInConstructor2.ts(4,24): error TS2300: Duplicate identifier 'names'. @@ -8,7 +8,8 @@ tests/cases/compiler/parameterPropertyInConstructor2.ts(4,24): error TS2300: Dup class Customers { constructor(public names: string); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2394: Overload signature is not compatible with function implementation. +!!! error TS2394: This overload signature is not compatible with its implementation signature. +!!! related TS2750 tests/cases/compiler/parameterPropertyInConstructor2.ts:4:5: The implementation signature is declared here. ~~~~~~~~~~~~~~~~~~~~ !!! error TS2369: A parameter property is only allowed in a constructor implementation. constructor(public names: string, public ages: number) { diff --git a/tests/baselines/reference/parserClassDeclaration12.errors.txt b/tests/baselines/reference/parserClassDeclaration12.errors.txt index 130eaa3defd..453c4f13eba 100644 --- a/tests/baselines/reference/parserClassDeclaration12.errors.txt +++ b/tests/baselines/reference/parserClassDeclaration12.errors.txt @@ -1,10 +1,11 @@ -tests/cases/conformance/parser/ecmascript5/ClassDeclarations/parserClassDeclaration12.ts(2,4): error TS2394: Overload signature is not compatible with function implementation. +tests/cases/conformance/parser/ecmascript5/ClassDeclarations/parserClassDeclaration12.ts(2,4): error TS2394: This overload signature is not compatible with its implementation signature. ==== tests/cases/conformance/parser/ecmascript5/ClassDeclarations/parserClassDeclaration12.ts (1 errors) ==== class C { constructor(); ~~~~~~~~~~~~~~ -!!! error TS2394: Overload signature is not compatible with function implementation. +!!! error TS2394: This overload signature is not compatible with its implementation signature. +!!! related TS2750 tests/cases/conformance/parser/ecmascript5/ClassDeclarations/parserClassDeclaration12.ts:3:4: The implementation signature is declared here. constructor(a) { } } \ No newline at end of file diff --git a/tests/baselines/reference/parserParameterList15.errors.txt b/tests/baselines/reference/parserParameterList15.errors.txt index 7a1a8af9093..cca41d94987 100644 --- a/tests/baselines/reference/parserParameterList15.errors.txt +++ b/tests/baselines/reference/parserParameterList15.errors.txt @@ -1,11 +1,12 @@ -tests/cases/conformance/parser/ecmascript5/ParameterLists/parserParameterList15.ts(1,10): error TS2394: Overload signature is not compatible with function implementation. +tests/cases/conformance/parser/ecmascript5/ParameterLists/parserParameterList15.ts(1,10): error TS2394: This overload signature is not compatible with its implementation signature. tests/cases/conformance/parser/ecmascript5/ParameterLists/parserParameterList15.ts(1,14): error TS2371: A parameter initializer is only allowed in a function or constructor implementation. ==== tests/cases/conformance/parser/ecmascript5/ParameterLists/parserParameterList15.ts (2 errors) ==== function foo(a = 4); ~~~ -!!! error TS2394: Overload signature is not compatible with function implementation. +!!! error TS2394: This overload signature is not compatible with its implementation signature. +!!! related TS2750 tests/cases/conformance/parser/ecmascript5/ParameterLists/parserParameterList15.ts:2:10: The implementation signature is declared here. ~~~~~ !!! error TS2371: A parameter initializer is only allowed in a function or constructor implementation. function foo(a, b) {} \ No newline at end of file diff --git a/tests/baselines/reference/parserParameterList16.errors.txt b/tests/baselines/reference/parserParameterList16.errors.txt index 4b30b386e6f..7d496cc03ea 100644 --- a/tests/baselines/reference/parserParameterList16.errors.txt +++ b/tests/baselines/reference/parserParameterList16.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/ParameterLists/parserParameterList16.ts(2,4): error TS2394: Overload signature is not compatible with function implementation. +tests/cases/conformance/parser/ecmascript5/ParameterLists/parserParameterList16.ts(2,4): error TS2394: This overload signature is not compatible with its implementation signature. tests/cases/conformance/parser/ecmascript5/ParameterLists/parserParameterList16.ts(2,8): error TS2371: A parameter initializer is only allowed in a function or constructor implementation. @@ -6,7 +6,8 @@ tests/cases/conformance/parser/ecmascript5/ParameterLists/parserParameterList16. class C { foo(a = 4); ~~~ -!!! error TS2394: Overload signature is not compatible with function implementation. +!!! error TS2394: This overload signature is not compatible with its implementation signature. +!!! related TS2750 tests/cases/conformance/parser/ecmascript5/ParameterLists/parserParameterList16.ts:3:4: The implementation signature is declared here. ~~~~~ !!! error TS2371: A parameter initializer is only allowed in a function or constructor implementation. foo(a, b) { } diff --git a/tests/baselines/reference/parserParameterList17.errors.txt b/tests/baselines/reference/parserParameterList17.errors.txt index a75e3c3b712..025c2eabbba 100644 --- a/tests/baselines/reference/parserParameterList17.errors.txt +++ b/tests/baselines/reference/parserParameterList17.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/ParameterLists/parserParameterList17.ts(2,4): error TS2394: Overload signature is not compatible with function implementation. +tests/cases/conformance/parser/ecmascript5/ParameterLists/parserParameterList17.ts(2,4): error TS2394: This overload signature is not compatible with its implementation signature. tests/cases/conformance/parser/ecmascript5/ParameterLists/parserParameterList17.ts(2,16): error TS2371: A parameter initializer is only allowed in a function or constructor implementation. @@ -6,7 +6,8 @@ tests/cases/conformance/parser/ecmascript5/ParameterLists/parserParameterList17. class C { constructor(a = 4); ~~~~~~~~~~~~~~~~~~~ -!!! error TS2394: Overload signature is not compatible with function implementation. +!!! error TS2394: This overload signature is not compatible with its implementation signature. +!!! related TS2750 tests/cases/conformance/parser/ecmascript5/ParameterLists/parserParameterList17.ts:3:4: The implementation signature is declared here. ~~~~~ !!! error TS2371: A parameter initializer is only allowed in a function or constructor implementation. constructor(a, b) { } diff --git a/tests/baselines/reference/recursiveFunctionTypes.errors.txt b/tests/baselines/reference/recursiveFunctionTypes.errors.txt index 77010d7efa1..cf30a4ff273 100644 --- a/tests/baselines/reference/recursiveFunctionTypes.errors.txt +++ b/tests/baselines/reference/recursiveFunctionTypes.errors.txt @@ -7,7 +7,7 @@ tests/cases/compiler/recursiveFunctionTypes.ts(12,16): error TS2355: A function tests/cases/compiler/recursiveFunctionTypes.ts(17,5): error TS2322: Type '() => I' is not assignable to type 'number'. tests/cases/compiler/recursiveFunctionTypes.ts(22,5): error TS2345: Argument of type '3' is not assignable to parameter of type '(t: typeof g) => void'. tests/cases/compiler/recursiveFunctionTypes.ts(25,1): error TS2322: Type '3' is not assignable to type '() => any'. -tests/cases/compiler/recursiveFunctionTypes.ts(30,10): error TS2394: Overload signature is not compatible with function implementation. +tests/cases/compiler/recursiveFunctionTypes.ts(30,10): error TS2394: This overload signature is not compatible with its implementation signature. tests/cases/compiler/recursiveFunctionTypes.ts(33,1): error TS2554: Expected 0-1 arguments, but got 2. tests/cases/compiler/recursiveFunctionTypes.ts(34,4): error TS2345: Argument of type '""' is not assignable to parameter of type '{ (): typeof f6; (a: typeof f6): () => number; }'. tests/cases/compiler/recursiveFunctionTypes.ts(42,1): error TS2554: Expected 0-1 arguments, but got 2. @@ -63,7 +63,8 @@ tests/cases/compiler/recursiveFunctionTypes.ts(43,4): error TS2345: Argument of function f6(): typeof f6; function f6(a: typeof f6): () => number; ~~ -!!! error TS2394: Overload signature is not compatible with function implementation. +!!! error TS2394: This overload signature is not compatible with its implementation signature. +!!! related TS2750 tests/cases/compiler/recursiveFunctionTypes.ts:31:10: The implementation signature is declared here. function f6(a?: any) { return f6; } f6("", 3); // error (arity mismatch) diff --git a/tests/baselines/reference/specializedSignatureIsNotSubtypeOfNonSpecializedSignature.errors.txt b/tests/baselines/reference/specializedSignatureIsNotSubtypeOfNonSpecializedSignature.errors.txt index 0e9454b9018..e6dd1aa26ee 100644 --- a/tests/baselines/reference/specializedSignatureIsNotSubtypeOfNonSpecializedSignature.errors.txt +++ b/tests/baselines/reference/specializedSignatureIsNotSubtypeOfNonSpecializedSignature.errors.txt @@ -1,10 +1,11 @@ -tests/cases/conformance/types/objectTypeLiteral/callSignatures/specializedSignatureIsNotSubtypeOfNonSpecializedSignature.ts(1,10): error TS2394: Overload signature is not compatible with function implementation. +tests/cases/conformance/types/objectTypeLiteral/callSignatures/specializedSignatureIsNotSubtypeOfNonSpecializedSignature.ts(1,10): error TS2394: This overload signature is not compatible with its implementation signature. ==== tests/cases/conformance/types/objectTypeLiteral/callSignatures/specializedSignatureIsNotSubtypeOfNonSpecializedSignature.ts (1 errors) ==== function foo(x: 'a'); ~~~ -!!! error TS2394: Overload signature is not compatible with function implementation. +!!! error TS2394: This overload signature is not compatible with its implementation signature. +!!! related TS2750 tests/cases/conformance/types/objectTypeLiteral/callSignatures/specializedSignatureIsNotSubtypeOfNonSpecializedSignature.ts:2:10: The implementation signature is declared here. function foo(x: number) { } class C { diff --git a/tests/baselines/reference/stringLiteralTypesOverloads05.errors.txt b/tests/baselines/reference/stringLiteralTypesOverloads05.errors.txt index 027feb7cc31..4353264b649 100644 --- a/tests/baselines/reference/stringLiteralTypesOverloads05.errors.txt +++ b/tests/baselines/reference/stringLiteralTypesOverloads05.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/types/stringLiteral/stringLiteralTypesOverloads05.ts(6,10): error TS2394: Overload signature is not compatible with function implementation. +tests/cases/conformance/types/stringLiteral/stringLiteralTypesOverloads05.ts(6,10): error TS2394: This overload signature is not compatible with its implementation signature. ==== tests/cases/conformance/types/stringLiteral/stringLiteralTypesOverloads05.ts (1 errors) ==== @@ -9,7 +9,8 @@ tests/cases/conformance/types/stringLiteral/stringLiteralTypesOverloads05.ts(6,1 function doThing(x: "dog"): Dog; ~~~~~~~ -!!! error TS2394: Overload signature is not compatible with function implementation. +!!! error TS2394: This overload signature is not compatible with its implementation signature. +!!! related TS2750 tests/cases/conformance/types/stringLiteral/stringLiteralTypesOverloads05.ts:9:10: The implementation signature is declared here. function doThing(x: "cat"): Cat; function doThing(x: string): Animal; function doThing(x: string, y?: string): Moose { diff --git a/tests/baselines/reference/templateStringInFunctionParameterType.errors.txt b/tests/baselines/reference/templateStringInFunctionParameterType.errors.txt index e523b4c2dcb..256d9dc1e91 100644 --- a/tests/baselines/reference/templateStringInFunctionParameterType.errors.txt +++ b/tests/baselines/reference/templateStringInFunctionParameterType.errors.txt @@ -1,5 +1,5 @@ tests/cases/conformance/es6/templates/templateStringInFunctionParameterType.ts(1,10): error TS2391: Function implementation is missing or not immediately following the declaration. -tests/cases/conformance/es6/templates/templateStringInFunctionParameterType.ts(1,10): error TS2394: Overload signature is not compatible with function implementation. +tests/cases/conformance/es6/templates/templateStringInFunctionParameterType.ts(1,10): error TS2394: This overload signature is not compatible with its implementation signature. tests/cases/conformance/es6/templates/templateStringInFunctionParameterType.ts(1,12): error TS1138: Parameter declaration expected. tests/cases/conformance/es6/templates/templateStringInFunctionParameterType.ts(1,19): error TS1005: ';' expected. @@ -9,7 +9,8 @@ tests/cases/conformance/es6/templates/templateStringInFunctionParameterType.ts(1 ~ !!! error TS2391: Function implementation is missing or not immediately following the declaration. ~ -!!! error TS2394: Overload signature is not compatible with function implementation. +!!! error TS2394: This overload signature is not compatible with its implementation signature. +!!! related TS2750 tests/cases/conformance/es6/templates/templateStringInFunctionParameterType.ts:3:10: The implementation signature is declared here. ~~~~~~~ !!! error TS1138: Parameter declaration expected. ~ diff --git a/tests/baselines/reference/templateStringInFunctionParameterTypeES6.errors.txt b/tests/baselines/reference/templateStringInFunctionParameterTypeES6.errors.txt index be9c3556caf..feb068d4957 100644 --- a/tests/baselines/reference/templateStringInFunctionParameterTypeES6.errors.txt +++ b/tests/baselines/reference/templateStringInFunctionParameterTypeES6.errors.txt @@ -1,5 +1,5 @@ tests/cases/conformance/es6/templates/templateStringInFunctionParameterTypeES6.ts(1,10): error TS2391: Function implementation is missing or not immediately following the declaration. -tests/cases/conformance/es6/templates/templateStringInFunctionParameterTypeES6.ts(1,10): error TS2394: Overload signature is not compatible with function implementation. +tests/cases/conformance/es6/templates/templateStringInFunctionParameterTypeES6.ts(1,10): error TS2394: This overload signature is not compatible with its implementation signature. tests/cases/conformance/es6/templates/templateStringInFunctionParameterTypeES6.ts(1,12): error TS1138: Parameter declaration expected. tests/cases/conformance/es6/templates/templateStringInFunctionParameterTypeES6.ts(1,19): error TS1005: ';' expected. @@ -9,7 +9,8 @@ tests/cases/conformance/es6/templates/templateStringInFunctionParameterTypeES6.t ~ !!! error TS2391: Function implementation is missing or not immediately following the declaration. ~ -!!! error TS2394: Overload signature is not compatible with function implementation. +!!! error TS2394: This overload signature is not compatible with its implementation signature. +!!! related TS2750 tests/cases/conformance/es6/templates/templateStringInFunctionParameterTypeES6.ts:3:10: The implementation signature is declared here. ~~~~~~~ !!! error TS1138: Parameter declaration expected. ~ diff --git a/tests/baselines/reference/voidAsNonAmbiguousReturnType.errors.txt b/tests/baselines/reference/voidAsNonAmbiguousReturnType.errors.txt index ce8b52f316c..09dfef337b2 100644 --- a/tests/baselines/reference/voidAsNonAmbiguousReturnType.errors.txt +++ b/tests/baselines/reference/voidAsNonAmbiguousReturnType.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/voidAsNonAmbiguousReturnType_0.ts(1,17): error TS2394: Overload signature is not compatible with function implementation. +tests/cases/compiler/voidAsNonAmbiguousReturnType_0.ts(1,17): error TS2394: This overload signature is not compatible with its implementation signature. ==== tests/cases/compiler/voidAsNonAmbiguousReturnType_1.ts (0 errors) ==== @@ -12,6 +12,7 @@ tests/cases/compiler/voidAsNonAmbiguousReturnType_0.ts(1,17): error TS2394: Over ==== tests/cases/compiler/voidAsNonAmbiguousReturnType_0.ts (1 errors) ==== export function mkdirSync(path: string, mode?: number): void; ~~~~~~~~~ -!!! error TS2394: Overload signature is not compatible with function implementation. +!!! error TS2394: This overload signature is not compatible with its implementation signature. +!!! related TS2750 tests/cases/compiler/voidAsNonAmbiguousReturnType_0.ts:2:17: The implementation signature is declared here. export function mkdirSync(path: string, mode?: string): void {} \ No newline at end of file From 592396d40a250147a4637a8db9376ffa0a90ebaf Mon Sep 17 00:00:00 2001 From: Wenlu Wang Date: Fri, 22 Feb 2019 07:09:37 +0800 Subject: [PATCH 091/149] expose token flags and numeric flags (#29897) * expose token flags and numeric flags * hide hide useless token flags --- src/compiler/factory.ts | 4 ++-- src/compiler/types.ts | 8 +++++++- tests/baselines/reference/api/tsserverlibrary.d.ts | 10 +++++++++- tests/baselines/reference/api/typescript.d.ts | 10 +++++++++- 4 files changed, 27 insertions(+), 5 deletions(-) diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index 00d84192055..f303dcb47a6 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -89,10 +89,10 @@ namespace ts { return createLiteralFromNode(value); } - export function createNumericLiteral(value: string): NumericLiteral { + export function createNumericLiteral(value: string, numericLiteralFlags: TokenFlags = TokenFlags.None): NumericLiteral { const node = createSynthesizedNode(SyntaxKind.NumericLiteral); node.text = value; - node.numericLiteralFlags = 0; + node.numericLiteralFlags = numericLiteralFlags; return node; } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index c0ae3b99c44..cce869df44e 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -1648,20 +1648,26 @@ namespace ts { kind: SyntaxKind.NoSubstitutionTemplateLiteral; } - /* @internal */ export const enum TokenFlags { None = 0, + /* @internal */ PrecedingLineBreak = 1 << 0, + /* @internal */ PrecedingJSDocComment = 1 << 1, + /* @internal */ Unterminated = 1 << 2, + /* @internal */ ExtendedUnicodeEscape = 1 << 3, Scientific = 1 << 4, // e.g. `10e2` Octal = 1 << 5, // e.g. `0777` HexSpecifier = 1 << 6, // e.g. `0x00000000` BinarySpecifier = 1 << 7, // e.g. `0b0110010000000000` OctalSpecifier = 1 << 8, // e.g. `0o777` + /* @internal */ ContainsSeparator = 1 << 9, // e.g. `0b1100_0101` + /* @internal */ BinaryOrOctalSpecifier = BinarySpecifier | OctalSpecifier, + /* @internal */ NumericLiteralFlags = Scientific | Octal | HexSpecifier | BinaryOrOctalSpecifier | ContainsSeparator } diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 36c246c999f..fab6f905efc 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -997,6 +997,14 @@ declare namespace ts { interface NoSubstitutionTemplateLiteral extends LiteralExpression { kind: SyntaxKind.NoSubstitutionTemplateLiteral; } + enum TokenFlags { + None = 0, + Scientific = 16, + Octal = 32, + HexSpecifier = 64, + BinarySpecifier = 128, + OctalSpecifier = 256 + } interface NumericLiteral extends LiteralExpression { kind: SyntaxKind.NumericLiteral; } @@ -3670,7 +3678,7 @@ declare namespace ts { function createLiteral(value: number | PseudoBigInt): NumericLiteral; function createLiteral(value: boolean): BooleanLiteral; function createLiteral(value: string | number | PseudoBigInt | boolean): PrimaryExpression; - function createNumericLiteral(value: string): NumericLiteral; + function createNumericLiteral(value: string, numericLiteralFlags?: TokenFlags): NumericLiteral; function createBigIntLiteral(value: string): BigIntLiteral; function createStringLiteral(text: string): StringLiteral; function createRegularExpressionLiteral(text: string): RegularExpressionLiteral; diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index 15dbc080241..40e16bf55bd 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -997,6 +997,14 @@ declare namespace ts { interface NoSubstitutionTemplateLiteral extends LiteralExpression { kind: SyntaxKind.NoSubstitutionTemplateLiteral; } + enum TokenFlags { + None = 0, + Scientific = 16, + Octal = 32, + HexSpecifier = 64, + BinarySpecifier = 128, + OctalSpecifier = 256 + } interface NumericLiteral extends LiteralExpression { kind: SyntaxKind.NumericLiteral; } @@ -3670,7 +3678,7 @@ declare namespace ts { function createLiteral(value: number | PseudoBigInt): NumericLiteral; function createLiteral(value: boolean): BooleanLiteral; function createLiteral(value: string | number | PseudoBigInt | boolean): PrimaryExpression; - function createNumericLiteral(value: string): NumericLiteral; + function createNumericLiteral(value: string, numericLiteralFlags?: TokenFlags): NumericLiteral; function createBigIntLiteral(value: string): BigIntLiteral; function createStringLiteral(text: string): StringLiteral; function createRegularExpressionLiteral(text: string): RegularExpressionLiteral; From fb0dcd49871df214c1c5911ed9714ebb9d1d9951 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Thu, 21 Feb 2019 18:17:53 -0800 Subject: [PATCH 092/149] Have runtests always throw on failure, make rm stream signal end of read queue (#30035) --- scripts/build/tests.js | 9 ++------- scripts/build/utils.js | 1 + 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/scripts/build/tests.js b/scripts/build/tests.js index bcf5431b8d9..0ac65002ab8 100644 --- a/scripts/build/tests.js +++ b/scripts/build/tests.js @@ -140,13 +140,8 @@ async function runConsoleTests(runJs, defaultReporter, runInParallel, watchMode, await deleteTemporaryProjectOutput(); if (error !== undefined) { - if (watchMode) { - throw error; - } - else { - log.error(error); - process.exit(typeof errorStatus === "number" ? errorStatus : 2); - } + process.exitCode = typeof errorStatus === "number" ? errorStatus : 2; + throw error; } } exports.runConsoleTests = runConsoleTests; diff --git a/scripts/build/utils.js b/scripts/build/utils.js index 170c36adef6..f9e48c58256 100644 --- a/scripts/build/utils.js +++ b/scripts/build/utils.js @@ -340,6 +340,7 @@ function rm(dest, opts) { duplex.push(file); cb(); } + duplex.push(null); // signal end of read queue }; const duplex = new Duplex({ From 999eb0b9ed50d4824a1c4b5e03cf2bcdc3b97338 Mon Sep 17 00:00:00 2001 From: TypeScript Bot Date: Fri, 22 Feb 2019 08:56:15 -0800 Subject: [PATCH 093/149] Update user baselines (#30046) --- tests/baselines/reference/user/async.log | 2 +- .../user/chrome-devtools-frontend.log | 54 ++++++++----------- tests/baselines/reference/user/debug.log | 18 +++---- .../reference/user/follow-redirects.log | 14 +++-- 4 files changed, 40 insertions(+), 48 deletions(-) diff --git a/tests/baselines/reference/user/async.log b/tests/baselines/reference/user/async.log index 1477ce5faa6..10f2d38ca6c 100644 --- a/tests/baselines/reference/user/async.log +++ b/tests/baselines/reference/user/async.log @@ -51,7 +51,7 @@ node_modules/async/autoInject.js(160,28): error TS2695: Left side of comma opera node_modules/async/autoInject.js(164,14): error TS2695: Left side of comma operator is unused and has no side effects. node_modules/async/autoInject.js(168,6): error TS2695: Left side of comma operator is unused and has no side effects. node_modules/async/cargo.js(62,12): error TS2304: Cannot find name 'AsyncFunction'. -node_modules/async/cargo.js(67,14): error TS2591: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. +node_modules/async/cargo.js(67,14): error TS2749: 'module' refers to a value, but is being used as a type here. node_modules/async/cargo.js(67,20): error TS1005: '}' expected. node_modules/async/cargo.js(92,11): error TS2695: Left side of comma operator is unused and has no side effects. node_modules/async/compose.js(8,37): error TS2695: Left side of comma operator is unused and has no side effects. diff --git a/tests/baselines/reference/user/chrome-devtools-frontend.log b/tests/baselines/reference/user/chrome-devtools-frontend.log index 55c189a92d6..5d98e163938 100644 --- a/tests/baselines/reference/user/chrome-devtools-frontend.log +++ b/tests/baselines/reference/user/chrome-devtools-frontend.log @@ -19,12 +19,7 @@ node_modules/chrome-devtools-frontend/front_end/Runtime.js(77,16): error TS7014: node_modules/chrome-devtools-frontend/front_end/Runtime.js(78,16): error TS7014: Function type, which lacks return-type annotation, implicitly has an 'any' return type. node_modules/chrome-devtools-frontend/front_end/Runtime.js(95,28): error TS2339: Property 'response' does not exist on type 'EventTarget'. node_modules/chrome-devtools-frontend/front_end/Runtime.js(147,37): error TS2339: Property '_importScriptPathPrefix' does not exist on type 'Window'. -node_modules/chrome-devtools-frontend/front_end/Runtime.js(158,21): error TS2345: Argument of type 'Promise' is not assignable to parameter of type 'Promise'. - Type 'string' is not assignable to type 'undefined'. -node_modules/chrome-devtools-frontend/front_end/Runtime.js(161,5): error TS2322: Type 'Promise' is not assignable to type 'Promise'. - Type 'undefined[]' is not assignable to type 'undefined'. node_modules/chrome-devtools-frontend/front_end/Runtime.js(187,12): error TS2339: Property 'eval' does not exist on type 'Window'. -node_modules/chrome-devtools-frontend/front_end/Runtime.js(197,5): error TS2322: Type 'Promise' is not assignable to type 'Promise'. node_modules/chrome-devtools-frontend/front_end/Runtime.js(267,14): error TS2339: Property 'runtime' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/Runtime.js(269,59): error TS2339: Property 'runtime' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/Runtime.js(270,9): error TS2322: Type 'Promise' is not assignable to type 'Promise'. @@ -38,7 +33,6 @@ node_modules/chrome-devtools-frontend/front_end/Runtime.js(693,7): error TS2322: Type 'boolean' is not assignable to type 'undefined'. node_modules/chrome-devtools-frontend/front_end/Runtime.js(705,5): error TS2322: Type 'Promise' is not assignable to type 'Promise'. node_modules/chrome-devtools-frontend/front_end/Runtime.js(715,7): error TS2322: Type 'Promise' is not assignable to type 'Promise'. -node_modules/chrome-devtools-frontend/front_end/Runtime.js(721,5): error TS2322: Type 'Promise' is not assignable to type 'Promise'. node_modules/chrome-devtools-frontend/front_end/Runtime.js(729,7): error TS2322: Type 'Promise' is not assignable to type 'Promise'. node_modules/chrome-devtools-frontend/front_end/Runtime.js(854,36): error TS2339: Property 'eval' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/Runtime.js(1083,15): error TS2355: A function whose declared type is neither 'void' nor 'any' must return a value. @@ -282,7 +276,7 @@ node_modules/chrome-devtools-frontend/front_end/animation/AnimationModel.js(514, node_modules/chrome-devtools-frontend/front_end/animation/AnimationModel.js(553,11): error TS2339: Property 'AnimationModel' does not exist on type '{ new (effect?: AnimationEffect, timeline?: AnimationTimeline): Animation; prototype: Animation; }'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationModel.js(583,43): error TS2339: Property 'remove' does not exist on type 'Map'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationModel.js(665,37): error TS2339: Property 'AnimationModel' does not exist on type '{ new (effect?: AnimationEffect, timeline?: AnimationTimeline): Animation; prototype: Animation; }'. -node_modules/chrome-devtools-frontend/front_end/animation/AnimationModel.js(691,24): error TS2304: Cannot find name 'Image'. +node_modules/chrome-devtools-frontend/front_end/animation/AnimationModel.js(691,24): error TS2749: 'Image' refers to a value, but is being used as a type here. node_modules/chrome-devtools-frontend/front_end/animation/AnimationModel.js(708,11): error TS2339: Property 'AnimationDispatcher' does not exist on type '{ new (effect?: AnimationEffect, timeline?: AnimationTimeline): Animation; prototype: Animation; }'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationModel.js(731,24): error TS2694: Namespace 'Protocol' has no exported member 'Animation'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationModel.js(741,11): error TS2339: Property 'AnimationModel' does not exist on type '{ new (effect?: AnimationEffect, timeline?: AnimationTimeline): Animation; prototype: Animation; }'. @@ -293,7 +287,7 @@ node_modules/chrome-devtools-frontend/front_end/animation/AnimationModel.js(782, node_modules/chrome-devtools-frontend/front_end/animation/AnimationModel.js(811,11): error TS2339: Property 'AnimationModel' does not exist on type '{ new (effect?: AnimationEffect, timeline?: AnimationTimeline): Animation; prototype: Animation; }'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationModel.js(811,44): error TS2300: Duplicate identifier 'Request'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationScreenshotPopover.js(7,11): error TS2339: Property 'AnimationScreenshotPopover' does not exist on type '{ new (effect?: AnimationEffect, timeline?: AnimationTimeline): Animation; prototype: Animation; }'. -node_modules/chrome-devtools-frontend/front_end/animation/AnimationScreenshotPopover.js(9,23): error TS2304: Cannot find name 'Image'. +node_modules/chrome-devtools-frontend/front_end/animation/AnimationScreenshotPopover.js(9,23): error TS2749: 'Image' refers to a value, but is being used as a type here. node_modules/chrome-devtools-frontend/front_end/animation/AnimationScreenshotPopover.js(18,39): error TS2345: Argument of type 'new (width?: number, height?: number) => HTMLImageElement' is not assignable to parameter of type 'Node'. Type 'new (width?: number, height?: number) => HTMLImageElement' is missing the following properties from type 'Node': baseURI, childNodes, firstChild, isConnected, and 47 more. node_modules/chrome-devtools-frontend/front_end/animation/AnimationScreenshotPopover.js(19,13): error TS2339: Property 'style' does not exist on type 'new (width?: number, height?: number) => HTMLImageElement'. @@ -345,7 +339,7 @@ node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(1 node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(173,25): error TS2339: Property 'boxInWindow' does not exist on type 'EventTarget'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(176,44): error TS2339: Property 'keysArray' does not exist on type 'Map'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(177,63): error TS2339: Property 'parentElement' does not exist on type 'EventTarget'. -node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(194,30): error TS2304: Cannot find name 'Image'. +node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(194,30): error TS2749: 'Image' refers to a value, but is being used as a type here. node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(197,25): error TS2339: Property 'AnimationScreenshotPopover' does not exist on type '{ new (effect?: AnimationEffect, timeline?: AnimationTimeline): Animation; prototype: Animation; }'. node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(208,50): error TS2554: Expected 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/animation/AnimationTimeline.js(208,67): error TS2554: Expected 2 arguments, but got 1. @@ -451,7 +445,7 @@ node_modules/chrome-devtools-frontend/front_end/application_test_runner/CacheSto node_modules/chrome-devtools-frontend/front_end/application_test_runner/CacheStorageTestRunner.js(19,13): error TS2339: Property 'resources' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/application_test_runner/CacheStorageTestRunner.js(21,37): error TS2339: Property 'resources' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/application_test_runner/CacheStorageTestRunner.js(32,5): error TS2552: Cannot find name 'promise'. Did you mean 'Promise'? -node_modules/chrome-devtools-frontend/front_end/application_test_runner/CacheStorageTestRunner.js(40,11): error TS2304: Cannot find name 'promise'. +node_modules/chrome-devtools-frontend/front_end/application_test_runner/CacheStorageTestRunner.js(40,11): error TS2552: Cannot find name 'promise'. Did you mean 'Promise'? node_modules/chrome-devtools-frontend/front_end/application_test_runner/CacheStorageTestRunner.js(61,13): error TS2339: Property 'resources' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/application_test_runner/CacheStorageTestRunner.js(68,37): error TS2339: Property 'resources' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/application_test_runner/CacheStorageTestRunner.js(70,13): error TS2339: Property 'resources' does not exist on type 'any[]'. @@ -719,10 +713,11 @@ node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighth node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(15630,28): error TS2304: Cannot find name 'fs'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(15636,30): error TS2304: Cannot find name 'fs'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(15645,18): error TS2304: Cannot find name 'fs'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(15684,1): error TS2322: Type 'Promise' is not assignable to type 'Promise'. - Type 'void' is not assignable to type 'any[]'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(15684,1): error TS2322: Type 'Promise' is not assignable to type 'Promise'. + Type 'void | any[]' is not assignable to type 'any[]'. + Type 'void' is not assignable to type 'any[]'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(15687,1): error TS2304: Cannot find name 'fs'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(15694,1): error TS2322: Type 'Promise' is not assignable to type 'Promise'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(15694,1): error TS2322: Type 'Promise' is not assignable to type 'Promise'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(15695,1): error TS2304: Cannot find name 'fs'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(15695,78): error TS2345: Argument of type '0' is not assignable to parameter of type '(string | number)[]'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(15791,19): error TS2304: Cannot find name 'fs'. @@ -744,15 +739,17 @@ node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighth node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(17501,1): error TS2322: Type 'any[]' is not assignable to type 'string'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(18010,1): error TS2554: Expected 0 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(19499,6): error TS2339: Property 'Util' does not exist on type 'Window'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(19585,1): error TS2322: Type 'Promise<{ artifacts: any; auditResults: any[]; }>' is not assignable to type 'Promise'. - Type '{ artifacts: any; auditResults: any[]; }' is not assignable to type 'void'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(19585,1): error TS2322: Type 'Promise' is not assignable to type 'Promise'. + Type 'void | { artifacts: any; auditResults: any[]; }' is not assignable to type 'void'. + Type '{ artifacts: any; auditResults: any[]; }' is not assignable to type 'void'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(19591,15): error TS2339: Property 'artifacts' does not exist on type 'void'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(19592,42): error TS2339: Property 'artifacts' does not exist on type 'void'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(19597,31): error TS2339: Property 'auditResults' does not exist on type 'void'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(19605,22): error TS2339: Property 'artifacts' does not exist on type 'void'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(19612,22): error TS2339: Property 'artifacts' does not exist on type 'void'. -node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(19683,1): error TS2322: Type 'Promise' is not assignable to type 'Promise'. - Type 'number' is not assignable to type 'void'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(19683,1): error TS2322: Type 'Promise' is not assignable to type 'Promise'. + Type 'number | void' is not assignable to type 'void'. + Type 'number' is not assignable to type 'void'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(19744,7): error TS2339: Property 'expected' does not exist on type 'Error'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(20005,8): error TS2339: Property 'runLighthouseForConnection' does not exist on type 'Window'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(20035,8): error TS2339: Property 'runLighthouseInWorker' does not exist on type 'Window'. @@ -3094,8 +3091,6 @@ node_modules/chrome-devtools-frontend/front_end/bindings/BlackboxManager.js(341, node_modules/chrome-devtools-frontend/front_end/bindings/BlackboxManager.js(351,31): error TS2694: Namespace 'Protocol' has no exported member 'Debugger'. node_modules/chrome-devtools-frontend/front_end/bindings/BlackboxManager.js(362,31): error TS2694: Namespace 'Protocol' has no exported member 'Debugger'. node_modules/chrome-devtools-frontend/front_end/bindings/BlackboxManager.js(375,9): error TS2322: Type 'Promise' is not assignable to type 'Promise'. -node_modules/chrome-devtools-frontend/front_end/bindings/BlackboxManager.js(378,9): error TS2322: Type 'Promise' is not assignable to type 'Promise'. -node_modules/chrome-devtools-frontend/front_end/bindings/BlackboxManager.js(381,5): error TS2322: Type 'Promise' is not assignable to type 'Promise'. node_modules/chrome-devtools-frontend/front_end/bindings/BreakpointManager.js(60,52): error TS2345: Argument of type 'this' is not assignable to parameter of type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. Type 'BreakpointManager' is not assignable to type '{ modelAdded(model: T): void; modelRemoved(model: T): void; }'. Types of property 'modelAdded' are incompatible. @@ -5791,7 +5786,6 @@ node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(28 node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(2906,7): error TS2322: Type 'Promise' is not assignable to type 'Promise'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(2910,7): error TS2322: Type 'Promise' is not assignable to type 'Promise'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(2918,7): error TS2322: Type 'Promise' is not assignable to type 'Promise'. -node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(2956,5): error TS2322: Type 'Promise' is not assignable to type 'Promise'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(2978,35): error TS2300: Duplicate identifier 'Context'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(2978,35): error TS2339: Property 'Context' does not exist on type 'typeof StylePropertyTreeElement'. node_modules/chrome-devtools-frontend/front_end/elements/StylesSidebarPane.js(3021,19): error TS2339: Property 'key' does not exist on type 'Event'. @@ -6917,7 +6911,7 @@ node_modules/chrome-devtools-frontend/front_end/layer_viewer/Layers3DView.js(794 node_modules/chrome-devtools-frontend/front_end/layer_viewer/Layers3DView.js(795,22): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/layer_viewer/Layers3DView.js(796,22): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/layer_viewer/Layers3DView.js(841,14): error TS7014: Function type, which lacks return-type annotation, implicitly has an 'any' return type. -node_modules/chrome-devtools-frontend/front_end/layer_viewer/Layers3DView.js(852,15): error TS2304: Cannot find name 'Image'. +node_modules/chrome-devtools-frontend/front_end/layer_viewer/Layers3DView.js(852,15): error TS2749: 'Image' refers to a value, but is being used as a type here. node_modules/chrome-devtools-frontend/front_end/layer_viewer/Layers3DView.js(858,13): error TS2339: Property 'image' does not exist on type 'WebGLTexture'. node_modules/chrome-devtools-frontend/front_end/layer_viewer/Layers3DView.js(861,81): error TS2339: Property 'image' does not exist on type 'WebGLTexture'. node_modules/chrome-devtools-frontend/front_end/layer_viewer/Layers3DView.js(928,26): error TS2694: Namespace 'SDK' has no exported member 'SnapshotWithRect'. @@ -7936,7 +7930,6 @@ node_modules/chrome-devtools-frontend/front_end/perf_ui/FilmStripView.js(254,19) node_modules/chrome-devtools-frontend/front_end/perf_ui/FilmStripView.js(256,35): error TS2339: Property 'metaKey' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/perf_ui/FilmStripView.js(263,35): error TS2339: Property 'metaKey' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/perf_ui/FilmStripView.js(306,51): error TS2339: Property 'millisToString' does not exist on type 'NumberConstructor'. -node_modules/chrome-devtools-frontend/front_end/perf_ui/FilmStripView.js(307,5): error TS2322: Type 'Promise' is not assignable to type 'Promise'. node_modules/chrome-devtools-frontend/front_end/perf_ui/FlameChart.js(307,36): error TS2339: Property 'offsetX' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/perf_ui/FlameChart.js(308,36): error TS2339: Property 'offsetY' does not exist on type 'Event'. node_modules/chrome-devtools-frontend/front_end/perf_ui/FlameChart.js(313,45): error TS2339: Property 'offsetX' does not exist on type 'Event'. @@ -10269,8 +10262,6 @@ node_modules/chrome-devtools-frontend/front_end/sdk/RemoteObject.js(1179,3): err Types of parameters 'functionDeclaration' and 'functionDeclaration' are incompatible. node_modules/chrome-devtools-frontend/front_end/sdk/RemoteObject.js(1234,21): error TS2694: Namespace 'SDK' has no exported member 'CallFunctionResult'. node_modules/chrome-devtools-frontend/front_end/sdk/RemoteObject.js(1265,21): error TS2694: Namespace 'SDK' has no exported member 'CallFunctionResult'. -node_modules/chrome-devtools-frontend/front_end/sdk/RemoteObject.js(1325,5): error TS2322: Type 'Promise<{ properties: RemoteObjectProperty[]; internalProperties: RemoteObjectProperty[]; }>' is not assignable to type 'Promise'. - Type '{ properties: RemoteObjectProperty[]; internalProperties: RemoteObjectProperty[]; }' is missing the following properties from type 'RemoteObject': customPreview, objectId, type, subtype, and 20 more. node_modules/chrome-devtools-frontend/front_end/sdk/RemoteObject.js(1345,43): error TS2694: Namespace 'SDK.DebuggerModel' has no exported member 'FunctionDetails'. node_modules/chrome-devtools-frontend/front_end/sdk/RemoteObject.js(1352,45): error TS2694: Namespace 'SDK.DebuggerModel' has no exported member 'FunctionDetails'. node_modules/chrome-devtools-frontend/front_end/sdk/RemoteObject.js(1363,35): error TS2694: Namespace 'SDK.DebuggerModel' has no exported member 'FunctionDetails'. @@ -11058,7 +11049,6 @@ node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptBreakpointsSid node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptBreakpointsSidebarPane.js(80,71): error TS2339: Property 'uiLocation' does not exist on type 'V'. node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptBreakpointsSidebarPane.js(81,60): error TS2339: Property 'breakpoint' does not exist on type 'V'. node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptBreakpointsSidebarPane.js(82,62): error TS2339: Property 'breakpoint' does not exist on type 'V'. -node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptBreakpointsSidebarPane.js(119,5): error TS2322: Type 'Promise' is not assignable to type 'Promise'. node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptBreakpointsSidebarPane.js(131,38): error TS2554: Expected 0 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptBreakpointsSidebarPane.js(141,29): error TS2339: Property 'enclosingNodeOrSelfWithClass' does not exist on type 'EventTarget'. node_modules/chrome-devtools-frontend/front_end/sources/JavaScriptBreakpointsSidebarPane.js(156,33): error TS2339: Property 'checkboxElement' does not exist on type 'EventTarget'. @@ -11258,9 +11248,6 @@ node_modules/chrome-devtools-frontend/front_end/sources/SnippetsPlugin.js(41,73) node_modules/chrome-devtools-frontend/front_end/sources/SourceFormatter.js(48,22): error TS2694: Namespace 'Common' has no exported member 'Event'. node_modules/chrome-devtools-frontend/front_end/sources/SourceFormatter.js(55,32): error TS2339: Property 'remove' does not exist on type 'Map; formatData: SourceFormatData; }>'. node_modules/chrome-devtools-frontend/front_end/sources/SourceFormatter.js(67,32): error TS2339: Property 'remove' does not exist on type 'Map; formatData: SourceFormatData; }>'. -node_modules/chrome-devtools-frontend/front_end/sources/SourceMapNamesResolver.js(55,5): error TS2322: Type 'Promise<{ name: string; offset: number; }[]>' is not assignable to type 'Promise'. - Type '{ name: string; offset: number; }[]' is not assignable to type 'Identifier[]'. - Type '{ name: string; offset: number; }' is missing the following properties from type 'Identifier': lineNumber, columnNumber node_modules/chrome-devtools-frontend/front_end/sources/SourceMapNamesResolver.js(304,37): error TS2339: Property 'inverse' does not exist on type 'Map'. node_modules/chrome-devtools-frontend/front_end/sources/SourceMapNamesResolver.js(322,32): error TS2694: Namespace 'SDK.RuntimeModel' has no exported member 'EvaluationResult'. node_modules/chrome-devtools-frontend/front_end/sources/SourceMapNamesResolver.js(361,25): error TS2694: Namespace 'Protocol' has no exported member 'Runtime'. @@ -11935,8 +11922,9 @@ node_modules/chrome-devtools-frontend/front_end/timeline/TimelineEventOverview.j node_modules/chrome-devtools-frontend/front_end/timeline/TimelineEventOverview.js(204,36): error TS2339: Property '_overviewIndex' does not exist on type 'TimelineCategory'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineEventOverview.js(246,68): error TS2339: Property 'peekLast' does not exist on type 'any[]'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineEventOverview.js(248,81): error TS2339: Property '_overviewIndex' does not exist on type 'TimelineCategory'. -node_modules/chrome-devtools-frontend/front_end/timeline/TimelineEventOverview.js(384,7): error TS2322: Type 'Promise HTMLImageElement>' is not assignable to type 'Promise'. - Type 'new (width?: number, height?: number) => HTMLImageElement' is missing the following properties from type 'HTMLImageElement': align, alt, border, complete, and 261 more. +node_modules/chrome-devtools-frontend/front_end/timeline/TimelineEventOverview.js(384,7): error TS2322: Type 'Promise HTMLImageElement)>' is not assignable to type 'Promise'. + Type 'HTMLImageElement | (new (width?: number, height?: number) => HTMLImageElement)' is not assignable to type 'HTMLImageElement'. + Type 'new (width?: number, height?: number) => HTMLImageElement' is missing the following properties from type 'HTMLImageElement': align, alt, border, complete, and 261 more. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineEventOverview.js(457,17): error TS2339: Property 'createChild' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineEventOverview.js(483,24): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineEventOverview.js(524,28): error TS2339: Property 'peekLast' does not exist on type 'TimelineFrame[]'. @@ -11951,7 +11939,7 @@ node_modules/chrome-devtools-frontend/front_end/timeline/TimelineFlameChartDataP node_modules/chrome-devtools-frontend/front_end/timeline/TimelineFlameChartDataProvider.js(111,16): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineFlameChartDataProvider.js(140,27): error TS2339: Property '_blackboxRoot' does not exist on type 'string | Event | TimelineFrame | Frame'. Property '_blackboxRoot' does not exist on type 'string'. -node_modules/chrome-devtools-frontend/front_end/timeline/TimelineFlameChartDataProvider.js(171,49): error TS2304: Cannot find name 'Image'. +node_modules/chrome-devtools-frontend/front_end/timeline/TimelineFlameChartDataProvider.js(171,49): error TS2749: 'Image' refers to a value, but is being used as a type here. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineFlameChartDataProvider.js(203,24): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineFlameChartDataProvider.js(222,11): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/timeline/TimelineFlameChartDataProvider.js(225,11): error TS2555: Expected at least 2 arguments, but got 1. @@ -13419,10 +13407,10 @@ node_modules/chrome-devtools-frontend/front_end/ui/UIUtils.js(1910,22): error TS node_modules/chrome-devtools-frontend/front_end/ui/UIUtils.js(1911,22): error TS2339: Property 'constrain' does not exist on type 'NumberConstructor'. node_modules/chrome-devtools-frontend/front_end/ui/UIUtils.js(1912,22): error TS2339: Property 'constrain' does not exist on type 'NumberConstructor'. node_modules/chrome-devtools-frontend/front_end/ui/UIUtils.js(1913,22): error TS2339: Property 'constrain' does not exist on type 'NumberConstructor'. -node_modules/chrome-devtools-frontend/front_end/ui/UIUtils.js(1938,23): error TS2304: Cannot find name 'Image'. +node_modules/chrome-devtools-frontend/front_end/ui/UIUtils.js(1938,23): error TS2749: 'Image' refers to a value, but is being used as a type here. node_modules/chrome-devtools-frontend/front_end/ui/UIUtils.js(1943,50): error TS2345: Argument of type 'HTMLImageElement' is not assignable to parameter of type '(new (width?: number, height?: number) => HTMLImageElement) | PromiseLike HTMLImageElement>'. Property 'then' is missing in type 'HTMLImageElement' but required in type 'PromiseLike HTMLImageElement>'. -node_modules/chrome-devtools-frontend/front_end/ui/UIUtils.js(1951,23): error TS2304: Cannot find name 'Image'. +node_modules/chrome-devtools-frontend/front_end/ui/UIUtils.js(1951,23): error TS2749: 'Image' refers to a value, but is being used as a type here. node_modules/chrome-devtools-frontend/front_end/ui/UIUtils.js(1961,12): error TS7014: Function type, which lacks return-type annotation, implicitly has an 'any' return type. node_modules/chrome-devtools-frontend/front_end/ui/UIUtils.js(1966,23): error TS2339: Property 'type' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/ui/UIUtils.js(1967,23): error TS2339: Property 'style' does not exist on type 'Element'. diff --git a/tests/baselines/reference/user/debug.log b/tests/baselines/reference/user/debug.log index 78c472d877f..4879bb3f8b3 100644 --- a/tests/baselines/reference/user/debug.log +++ b/tests/baselines/reference/user/debug.log @@ -53,21 +53,21 @@ node_modules/debug/src/browser.js(45,138): error TS2551: Property 'WebkitAppeara node_modules/debug/src/browser.js(46,70): error TS2339: Property 'firebug' does not exist on type 'Console'. node_modules/debug/src/browser.js(100,148): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type '[any?, ...any[]]'. node_modules/debug/src/browser.js(152,13): error TS2304: Cannot find name 'LocalStorage'. -node_modules/debug/src/common.js(51,24): error TS2339: Property 'colors' does not exist on type '{ (namespace: string): Function; debug: ...; default: ...; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. -node_modules/debug/src/common.js(51,60): error TS2339: Property 'colors' does not exist on type '{ (namespace: string): Function; debug: ...; default: ...; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. +node_modules/debug/src/common.js(51,24): error TS2339: Property 'colors' does not exist on type '{ (namespace: string): Function; debug: ...; default: ...; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: { (value: number, options?: { ...; } | undefined): string; (value: string): number; }; ... 4 more ...; selectColor: (namespace...'. +node_modules/debug/src/common.js(51,60): error TS2339: Property 'colors' does not exist on type '{ (namespace: string): Function; debug: ...; default: ...; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: { (value: number, options?: { ...; } | undefined): string; (value: string): number; }; ... 4 more ...; selectColor: (namespace...'. node_modules/debug/src/common.js(80,12): error TS2339: Property 'diff' does not exist on type '{ (...args: any[]): void; namespace: string; enabled: boolean; useColors: any; color: string | number; destroy: () => boolean; extend: (namespace: any, delimiter: any) => Function; }'. node_modules/debug/src/common.js(81,12): error TS2339: Property 'prev' does not exist on type '{ (...args: any[]): void; namespace: string; enabled: boolean; useColors: any; color: string | number; destroy: () => boolean; extend: (namespace: any, delimiter: any) => Function; }'. node_modules/debug/src/common.js(82,12): error TS2339: Property 'curr' does not exist on type '{ (...args: any[]): void; namespace: string; enabled: boolean; useColors: any; color: string | number; destroy: () => boolean; extend: (namespace: any, delimiter: any) => Function; }'. -node_modules/debug/src/common.js(113,19): error TS2551: Property 'formatArgs' does not exist on type '{ (namespace: string): Function; debug: ...; default: ...; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. Did you mean 'formatters'? +node_modules/debug/src/common.js(113,19): error TS2551: Property 'formatArgs' does not exist on type '{ (namespace: string): Function; debug: ...; default: ...; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: { (value: number, options?: { ...; } | undefined): string; (value: string): number; }; ... 4 more ...; selectColor: (namespace...'. Did you mean 'formatters'? node_modules/debug/src/common.js(114,24): error TS2339: Property 'log' does not exist on type '{ (...args: any[]): void; namespace: string; enabled: boolean; useColors: any; color: string | number; destroy: () => boolean; extend: (namespace: any, delimiter: any) => Function; }'. -node_modules/debug/src/common.js(114,43): error TS2339: Property 'log' does not exist on type '{ (namespace: string): Function; debug: ...; default: ...; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. -node_modules/debug/src/common.js(120,35): error TS2339: Property 'useColors' does not exist on type '{ (namespace: string): Function; debug: ...; default: ...; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. -node_modules/debug/src/common.js(127,28): error TS2339: Property 'init' does not exist on type '{ (namespace: string): Function; debug: ...; default: ...; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. -node_modules/debug/src/common.js(128,19): error TS2339: Property 'init' does not exist on type '{ (namespace: string): Function; debug: ...; default: ...; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. -node_modules/debug/src/common.js(159,17): error TS2339: Property 'save' does not exist on type '{ (namespace: string): Function; debug: ...; default: ...; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. +node_modules/debug/src/common.js(114,43): error TS2339: Property 'log' does not exist on type '{ (namespace: string): Function; debug: ...; default: ...; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: { (value: number, options?: { ...; } | undefined): string; (value: string): number; }; ... 4 more ...; selectColor: (namespace...'. +node_modules/debug/src/common.js(120,35): error TS2339: Property 'useColors' does not exist on type '{ (namespace: string): Function; debug: ...; default: ...; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: { (value: number, options?: { ...; } | undefined): string; (value: string): number; }; ... 4 more ...; selectColor: (namespace...'. +node_modules/debug/src/common.js(127,28): error TS2339: Property 'init' does not exist on type '{ (namespace: string): Function; debug: ...; default: ...; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: { (value: number, options?: { ...; } | undefined): string; (value: string): number; }; ... 4 more ...; selectColor: (namespace...'. +node_modules/debug/src/common.js(128,19): error TS2339: Property 'init' does not exist on type '{ (namespace: string): Function; debug: ...; default: ...; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: { (value: number, options?: { ...; } | undefined): string; (value: string): number; }; ... 4 more ...; selectColor: (namespace...'. +node_modules/debug/src/common.js(159,17): error TS2339: Property 'save' does not exist on type '{ (namespace: string): Function; debug: ...; default: ...; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: { (value: number, options?: { ...; } | undefined): string; (value: string): number; }; ... 4 more ...; selectColor: (namespace...'. node_modules/debug/src/common.js(230,13): error TS2304: Cannot find name 'Mixed'. node_modules/debug/src/common.js(231,14): error TS2304: Cannot find name 'Mixed'. -node_modules/debug/src/common.js(244,34): error TS2339: Property 'load' does not exist on type '{ (namespace: string): Function; debug: ...; default: ...; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: any; ... 4 more ...; selectColor: (namespace: string) => string | number; }'. +node_modules/debug/src/common.js(244,34): error TS2339: Property 'load' does not exist on type '{ (namespace: string): Function; debug: ...; default: ...; coerce: (val: any) => any; disable: () => void; enable: (namespaces: string) => void; enabled: (name: string) => boolean; humanize: { (value: number, options?: { ...; } | undefined): string; (value: string): number; }; ... 4 more ...; selectColor: (namespace...'. node_modules/debug/src/index.js(7,47): error TS2339: Property 'type' does not exist on type 'Process'. node_modules/debug/src/index.js(7,78): error TS2339: Property 'browser' does not exist on type 'Process'. node_modules/debug/src/index.js(7,106): error TS2339: Property '__nwjs' does not exist on type 'Process'. diff --git a/tests/baselines/reference/user/follow-redirects.log b/tests/baselines/reference/user/follow-redirects.log index 7e3f419696e..a5a92443227 100644 --- a/tests/baselines/reference/user/follow-redirects.log +++ b/tests/baselines/reference/user/follow-redirects.log @@ -2,12 +2,16 @@ Exit Code: 1 Standard output: node_modules/follow-redirects/index.js(105,10): error TS2339: Property 'emit' does not exist on type 'RedirectableRequest'. node_modules/follow-redirects/index.js(106,10): error TS2339: Property 'abort' does not exist on type 'RedirectableRequest'. -node_modules/follow-redirects/index.js(173,10): error TS2339: Property 'emit' does not exist on type 'RedirectableRequest'. -node_modules/follow-redirects/index.js(212,16): error TS2339: Property 'emit' does not exist on type 'RedirectableRequest'. -node_modules/follow-redirects/index.js(259,12): error TS2339: Property 'emit' does not exist on type 'RedirectableRequest'. -node_modules/follow-redirects/index.js(293,35): error TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'. +node_modules/follow-redirects/index.js(153,10): error TS2339: Property 'once' does not exist on type 'RedirectableRequest'. +node_modules/follow-redirects/index.js(156,12): error TS2339: Property 'socket' does not exist on type 'RedirectableRequest'. +node_modules/follow-redirects/index.js(166,8): error TS2339: Property 'once' does not exist on type 'RedirectableRequest'. +node_modules/follow-redirects/index.js(167,8): error TS2339: Property 'once' does not exist on type 'RedirectableRequest'. +node_modules/follow-redirects/index.js(206,10): error TS2339: Property 'emit' does not exist on type 'RedirectableRequest'. +node_modules/follow-redirects/index.js(245,16): error TS2339: Property 'emit' does not exist on type 'RedirectableRequest'. +node_modules/follow-redirects/index.js(292,12): error TS2339: Property 'emit' does not exist on type 'RedirectableRequest'. +node_modules/follow-redirects/index.js(326,35): error TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string'. -node_modules/follow-redirects/index.js(306,10): error TS2339: Property 'emit' does not exist on type 'RedirectableRequest'. +node_modules/follow-redirects/index.js(339,10): error TS2339: Property 'emit' does not exist on type 'RedirectableRequest'. From a41a27694ac9ca2848fb83cc0a5414c4c2c5338e Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Fri, 22 Feb 2019 13:12:11 -0800 Subject: [PATCH 094/149] Fix baseline-accept-rwc (#30052) --- Gulpfile.js | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/Gulpfile.js b/Gulpfile.js index 3367010f6bd..93770f9d498 100644 --- a/Gulpfile.js +++ b/Gulpfile.js @@ -473,22 +473,23 @@ task("diff").description = "Diffs the compiler baselines using the diff tool spe task("diff-rwc", () => exec(getDiffTool(), [refRwcBaseline, localRwcBaseline], { ignoreExitCode: true })); task("diff-rwc").description = "Diffs the RWC baselines using the diff tool specified by the 'DIFF' environment variable"; -const baselineAccept = subfolder => merge2( - src([`${localBaseline}${subfolder ? `${subfolder}/` : ``}**`, `!${localBaseline}${subfolder}/**/*.delete`], { base: localBaseline }) +/** + * @param {string} localBaseline Path to the local copy of the baselines + * @param {string} refBaseline Path to the reference copy of the baselines + */ +const baselineAccept = (localBaseline, refBaseline) => merge2( + src([`${localBaseline}/**`, `!${localBaseline}/**/*.delete`], { base: localBaseline }) .pipe(dest(refBaseline)), - src([`${localBaseline}${subfolder ? `${subfolder}/` : ``}**/*.delete`], { base: localBaseline, read: false }) + src([`${localBaseline}/**/*.delete`], { base: localBaseline, read: false }) .pipe(rm()) .pipe(rename({ extname: "" })) .pipe(rm(refBaseline))); -task("baseline-accept", () => baselineAccept("")); +task("baseline-accept", () => baselineAccept(localBaseline, refBaseline)); task("baseline-accept").description = "Makes the most recent test results the new baseline, overwriting the old baseline"; -task("baseline-accept-rwc", () => baselineAccept("rwc")); +task("baseline-accept-rwc", () => baselineAccept(localRwcBaseline, refRwcBaseline)); task("baseline-accept-rwc").description = "Makes the most recent rwc test results the new baseline, overwriting the old baseline"; -task("baseline-accept-test262", () => baselineAccept("test262")); -task("baseline-accept-test262").description = "Makes the most recent test262 test results the new baseline, overwriting the old baseline"; - // TODO(rbuckton): Determine if 'webhost' is still in use. const buildWebHost = () => buildProject("tests/webhost/webtsc.tsconfig.json"); task("webhost", series(lkgPreBuild, buildWebHost)); From ce42aa43a8b11a1fdae4313225d9e6012b3d70e7 Mon Sep 17 00:00:00 2001 From: Gabriela Araujo Britto Date: Fri, 22 Feb 2019 16:31:40 -0800 Subject: [PATCH 095/149] check usages of class if refactoring a constructor --- .../refactors/convertToNamedParameters.ts | 251 ++++++++++++------ 1 file changed, 166 insertions(+), 85 deletions(-) diff --git a/src/services/refactors/convertToNamedParameters.ts b/src/services/refactors/convertToNamedParameters.ts index 8d4f3d6e3c9..9bcea0e5983 100644 --- a/src/services/refactors/convertToNamedParameters.ts +++ b/src/services/refactors/convertToNamedParameters.ts @@ -31,9 +31,8 @@ namespace ts.refactor.convertToNamedParameters { const functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, program.getTypeChecker()); if (!functionDeclaration || !cancellationToken) return undefined; - const functionNames = getFunctionDeclarationNames(functionDeclaration); - const groupedReferences = getGroupedReferences(functionNames, program, cancellationToken); - if (checkReferences(functionNames, groupedReferences)) { + const groupedReferences = getGroupedReferences(functionDeclaration, program, cancellationToken); + if (groupedReferences.valid) { const edits = textChanges.ChangeTracker.with(context, t => doChange(file, program, host, t, functionDeclaration, groupedReferences)); return { renameFilename: undefined, renameLocation: undefined, edits }; } @@ -41,7 +40,6 @@ namespace ts.refactor.convertToNamedParameters { return { edits: [] }; } - function doChange(sourceFile: SourceFile, program: Program, host: LanguageServiceHost, changes: textChanges.ChangeTracker, functionDeclaration: ValidFunctionDeclaration, groupedReferences: GroupedReferences): void { const newParamDeclaration = map(createNewParameters(functionDeclaration, program, host), param => getSynthesizedDeepClone(param)); changes.replaceNodeRangeWithNodes( @@ -57,7 +55,7 @@ namespace ts.refactor.convertToNamedParameters { }); - const functionCalls = groupedReferences.calls; + const functionCalls = deduplicate(groupedReferences.functionCalls, (a, b) => a === b); forEach(functionCalls, call => { if (call.arguments && call.arguments.length) { const newArgument = getSynthesizedDeepClone(createNewArgument(functionDeclaration, call.arguments), /*includeTrivia*/ true); @@ -70,99 +68,172 @@ namespace ts.refactor.convertToNamedParameters { }}); } - function getGroupedReferences(functionNames: Node[], program: Program, cancellationToken: CancellationToken): GroupedReferences { - const functionReferences = flatMap(functionNames, name => FindAllReferences.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken)); - const groupedReferences = groupReferences(functionReferences); + function getGroupedReferences(functionDeclaration: ValidFunctionDeclaration, program: Program, cancellationToken: CancellationToken): GroupedReferences { + const names = getDeclarationNames(functionDeclaration); + const references = flatMap(names, name => FindAllReferences.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken)); + let groupedReferences = groupReferences(references); + + // if the refactored function is a constructor, we must also go through the references to its class + if (isConstructorDeclaration(functionDeclaration)) { + const className = getClassName(functionDeclaration); + groupedReferences = groupClassReferences(groupedReferences, className); + } + + validateReferences(groupedReferences); return groupedReferences; + function getClassName(constructorDeclaration: ValidConstructor): Identifier { + switch (constructorDeclaration.parent.kind) { + case SyntaxKind.ClassDeclaration: + return constructorDeclaration.parent.name; + case SyntaxKind.ClassExpression: + return constructorDeclaration.parent.parent.name; + } + } + function groupReferences(referenceEntries: ReadonlyArray | undefined): GroupedReferences { - const references: GroupedReferences = { calls: [], declarations: [], unhandled: [] }; + const groupedReferences: GroupedReferences = { functionCalls: [], declarations: [], unhandled: [], valid: true }; + forEach(referenceEntries, (entry) => { - const decl = entryToDeclarationName(entry); + const decl = entryToDeclaration(entry); if (decl) { - references.declarations.push(decl); + groupedReferences.declarations.push(decl); return; } + const call = entryToFunctionCall(entry); if (call) { - references.calls.push(call); + groupedReferences.functionCalls.push(call); return; } - const node = entryToNode(entry); - if (node) { - references.unhandled.push(node); - } - }); - return references; - function entryToFunctionCall(entry: FindAllReferences.Entry): CallExpression | NewExpression | undefined { - if (entry.kind !== FindAllReferences.EntryKind.Span && entry.node && entry.node.parent) { - const functionReference = entry.node; - const parent = functionReference.parent; - switch (parent.kind) { - // Function call (foo(...) or super(...)) - case SyntaxKind.CallExpression: - const callExpression = tryCast(parent, isCallExpression); - if (callExpression && callExpression.expression === functionReference) { - return callExpression; - } - break; - // Constructor call (new Foo(...)) - case SyntaxKind.NewExpression: - const newExpression = tryCast(parent, isNewExpression); - if (newExpression && newExpression.expression === functionReference) { - return newExpression; - } - break; - // Method call (x.foo(...)) - case SyntaxKind.PropertyAccessExpression: - const propertyAccessExpression = tryCast(parent, isPropertyAccessExpression); - if (propertyAccessExpression && propertyAccessExpression.parent && propertyAccessExpression.name === functionReference) { - const callExpression = tryCast(propertyAccessExpression.parent, isCallExpression); - if (callExpression && callExpression.expression === propertyAccessExpression) { - return callExpression; - } - } - break; - // Method call (x['foo'](...)) - case SyntaxKind.ElementAccessExpression: - const elementAccessExpression = tryCast(parent, isElementAccessExpression); - if (elementAccessExpression && elementAccessExpression.parent && elementAccessExpression.argumentExpression === functionReference) { - const callExpression = tryCast(elementAccessExpression.parent, isCallExpression); - if (callExpression && callExpression.expression === elementAccessExpression) { - return callExpression; - } - } - break; + groupedReferences.unhandled.push(entry); + }); + return groupedReferences; + } + + function groupClassReferences(groupedReferences: GroupedReferences, className: Identifier): GroupedReferences { + const classReferences: ClassReferences = { accessExpressions: [], typeUsages: [] }; + const unhandledEntries = groupedReferences.unhandled; + const newUnhandledEntries: FindAllReferences.Entry[] = []; + + forEach(unhandledEntries, (entry) => { + if (entry.kind === FindAllReferences.EntryKind.Node && entry.node.symbol === className.symbol) { + const accessExpression = entryToAccessExpression(entry); + if (accessExpression) { + classReferences.accessExpressions.push(accessExpression); + return; + } + + // Only class declarations are allowed to be used as a type (in a heritage clause), + // otherwise `findAllReferences` might not be able to track constructor calls. + if (isClassDeclaration(functionDeclaration.parent)) { + const type = entryToType(entry); + if (type) { + classReferences.typeUsages.push(type); + return; + } } } - return undefined; - } + newUnhandledEntries.push(entry); + }); - function entryToDeclarationName(entry: FindAllReferences.Entry): Node | undefined { - if (entry.kind !== FindAllReferences.EntryKind.Span && entry.node && contains(functionNames, entry.node)) { - return entry.node; + return { ...groupedReferences, classReferences, unhandled: newUnhandledEntries }; + } + + function validateReferences(groupedReferences: GroupedReferences): void { + if (groupedReferences.unhandled.length > 0) { + groupedReferences.valid = false; + } + if (!every(groupedReferences.declarations, decl => contains(names, decl))) { + groupedReferences.valid = false; + } + } + + function entryToFunctionCall(entry: FindAllReferences.Entry): CallExpression | NewExpression | undefined { + if (entry.kind === FindAllReferences.EntryKind.Node && entry.node.parent) { + const functionReference = entry.node; + const parent = functionReference.parent; + switch (parent.kind) { + // Function call (foo(...) or super(...)) + case SyntaxKind.CallExpression: + const callExpression = tryCast(parent, isCallExpression); + if (callExpression && callExpression.expression === functionReference) { + return callExpression; + } + break; + // Constructor call (new Foo(...)) + case SyntaxKind.NewExpression: + const newExpression = tryCast(parent, isNewExpression); + if (newExpression && newExpression.expression === functionReference) { + return newExpression; + } + break; + // Method call (x.foo(...)) + case SyntaxKind.PropertyAccessExpression: + const propertyAccessExpression = tryCast(parent, isPropertyAccessExpression); + if (propertyAccessExpression && propertyAccessExpression.parent && propertyAccessExpression.name === functionReference) { + const callExpression = tryCast(propertyAccessExpression.parent, isCallExpression); + if (callExpression && callExpression.expression === propertyAccessExpression) { + return callExpression; + } + } + break; + // Method call (x["foo"](...)) + case SyntaxKind.ElementAccessExpression: + const elementAccessExpression = tryCast(parent, isElementAccessExpression); + if (elementAccessExpression && elementAccessExpression.parent && elementAccessExpression.argumentExpression === functionReference) { + const callExpression = tryCast(elementAccessExpression.parent, isCallExpression); + if (callExpression && callExpression.expression === elementAccessExpression) { + return callExpression; + } + } + break; } - return undefined; } + return undefined; + } - function entryToNode(entry: FindAllReferences.Entry): Node | undefined { - if (entry.kind !== FindAllReferences.EntryKind.Span && entry.node) { - return entry.node; + function entryToDeclaration(entry: FindAllReferences.Entry): Node | undefined { + if (entry.kind === FindAllReferences.EntryKind.Node && contains(names, entry.node)) { + return entry.node; + } + return undefined; + } + + function entryToAccessExpression(entry: FindAllReferences.Entry): ElementAccessExpression | PropertyAccessExpression | undefined { + if (entry.kind === FindAllReferences.EntryKind.Node && entry.node.parent) { + const reference = entry.node; + const parent = reference.parent; + switch (parent.kind) { + // `C.foo` + case SyntaxKind.PropertyAccessExpression: + const propertyAccessExpression = tryCast(parent, isPropertyAccessExpression); + if (propertyAccessExpression && propertyAccessExpression.expression === reference) { + return propertyAccessExpression; + } + break; + // `C["foo"]` + case SyntaxKind.ElementAccessExpression: + const elementAccessExpression = tryCast(parent, isElementAccessExpression); + if (elementAccessExpression && elementAccessExpression.expression === reference) { + return elementAccessExpression; + } + break; } - return undefined; } + return undefined; } - } - function checkReferences(functionNames: Node[], groupedReferences: GroupedReferences): boolean { - if (groupedReferences.unhandled.length > 0) { - return false; + function entryToType(entry: FindAllReferences.Entry): Node | undefined { + if (entry.kind === FindAllReferences.EntryKind.Node) { + const reference = entry.node; + if (getMeaningFromLocation(reference) === SemanticMeaning.Type || isExpressionWithTypeArgumentsInClassExtendsClause(reference.parent)) { + return reference; + } + } + return undefined; } - if (groupedReferences.declarations.length > functionNames.length) { - return false; - } - return true; } function getFunctionDeclarationAtPosition(file: SourceFile, startPosition: number, checker: TypeChecker): ValidFunctionDeclaration | undefined { @@ -180,7 +251,7 @@ namespace ts.refactor.convertToNamedParameters { return !!functionDeclaration.name && !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration); case SyntaxKind.Constructor: if (isClassDeclaration(functionDeclaration.parent)) { - return !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration); + return !!functionDeclaration.body && !!functionDeclaration.parent.name && !checker.isImplementationOfOverload(functionDeclaration); } else { return isValidVariableDeclaration(functionDeclaration.parent.parent) && !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration); @@ -200,7 +271,7 @@ namespace ts.refactor.convertToNamedParameters { } function isValidVariableDeclaration(node: Node): node is ValidVariableDeclaration { - return isVariableDeclaration(node) && isVarConst(node) && !node.type; + return isVariableDeclaration(node) && isVarConst(node) && isIdentifier(node.name) && !node.type; } } @@ -359,7 +430,7 @@ namespace ts.refactor.convertToNamedParameters { return getTextOfIdentifierOrLiteral(paramDeclaration.name); } - function getFunctionDeclarationNames(functionDeclaration: ValidFunctionDeclaration): Node[] { + function getDeclarationNames(functionDeclaration: ValidFunctionDeclaration): Node[] { switch (functionDeclaration.kind) { case SyntaxKind.FunctionDeclaration: case SyntaxKind.MethodDeclaration: @@ -368,10 +439,14 @@ namespace ts.refactor.convertToNamedParameters { const ctrKeyword = findChildOfKind(functionDeclaration, SyntaxKind.ConstructorKeyword, functionDeclaration.getSourceFile())!; switch (functionDeclaration.parent.kind) { case SyntaxKind.ClassDeclaration: - return [ctrKeyword]; + const classDeclaration = functionDeclaration.parent; + return [classDeclaration.name, ctrKeyword]; case SyntaxKind.ClassExpression: - const name = functionDeclaration.parent.parent.name; - return [ctrKeyword, name]; + const classExpression = functionDeclaration.parent; + const variableDeclaration = functionDeclaration.parent.parent; + const className = classExpression.name; + if (className) return [className, ctrKeyword, variableDeclaration.name]; + return [ctrKeyword, variableDeclaration.name]; default: return Debug.assertNever(functionDeclaration.parent); } case SyntaxKind.ArrowFunction: @@ -384,10 +459,10 @@ namespace ts.refactor.convertToNamedParameters { type ValidParameterNodeArray = NodeArray; - type ValidVariableDeclaration = VariableDeclaration & { type: undefined }; + type ValidVariableDeclaration = VariableDeclaration & { name: Identifier, type: undefined }; interface ValidConstructor extends ConstructorDeclaration { - parent: ClassDeclaration | (ClassExpression & { parent: ValidVariableDeclaration }); + parent: (ClassDeclaration & { name: Identifier }) | (ClassExpression & { parent: ValidVariableDeclaration }); parameters: NodeArray; body: FunctionBody; } @@ -422,8 +497,14 @@ namespace ts.refactor.convertToNamedParameters { } interface GroupedReferences { - calls: (CallExpression | NewExpression)[]; + functionCalls: (CallExpression | NewExpression)[]; declarations: Node[]; - unhandled: Node[]; + classReferences?: ClassReferences; + unhandled: FindAllReferences.Entry[]; + valid: boolean; + } + interface ClassReferences { + accessExpressions: Node[]; + typeUsages: Node[]; } } \ No newline at end of file From 640424e42cb73ebaa63f10453afab7141dfa2bc2 Mon Sep 17 00:00:00 2001 From: Gabriela Araujo Britto Date: Fri, 22 Feb 2019 16:32:12 -0800 Subject: [PATCH 096/149] fix comment --- src/compiler/core.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 4bd4801ce8f..a47387a932e 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -917,7 +917,7 @@ namespace ts { /** * Deduplicates an unsorted array. - * @param equalityComparer An optional `EqualityComparer` used to determine if two values are duplicates. + * @param equalityComparer An `EqualityComparer` used to determine if two values are duplicates. * @param comparer An optional `Comparer` used to sort entries before comparison, though the * result will remain in the original order in `array`. */ From 21ab39649c0a090ef7bc1e7dfd701b5254947b61 Mon Sep 17 00:00:00 2001 From: Joseph Wunderlich Date: Fri, 22 Feb 2019 17:24:21 -0800 Subject: [PATCH 097/149] remove any annotation from declare method quickfix --- src/services/codefixes/helpers.ts | 2 +- .../fourslash/codeFixAddMissingMember9.ts | 2 +- .../fourslash/codeFixAddMissingMember_all.ts | 2 +- ...eFixAddMissingMember_generator_function.ts | 2 +- ...AddMissingMember_non_generator_function.ts | 2 +- .../codeFixUndeclaredAcrossFiles1.ts | 6 ++-- .../codeFixUndeclaredAcrossFiles3.ts | 2 +- .../codeFixUndeclaredInStaticMethod.ts | 14 ++++---- .../fourslash/codeFixUndeclaredMethod.ts | 12 +++---- .../codeFixUndeclaredMethodFunctionArgs.ts | 6 ++-- ...odeFixUndeclaredMethodObjectLiteralArgs.ts | 35 ++++++++++++++++++- 11 files changed, 59 insertions(+), 26 deletions(-) diff --git a/src/services/codefixes/helpers.ts b/src/services/codefixes/helpers.ts index ec86415b9fa..5f448653a78 100644 --- a/src/services/codefixes/helpers.ts +++ b/src/services/codefixes/helpers.ts @@ -156,7 +156,7 @@ namespace ts.codefix { isIdentifier(arg) ? arg.text : isPropertyAccessExpression(arg) ? arg.name.text : undefined); const contextualType = checker.getContextualType(call); - const returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, contextNode, /*flags*/ undefined, tracker) || createKeywordTypeNode(SyntaxKind.AnyKeyword); + const returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, contextNode, /*flags*/ undefined, tracker); return createMethod( /*decorators*/ undefined, /*modifiers*/ makeStatic ? [createToken(SyntaxKind.StaticKeyword)] : undefined, diff --git a/tests/cases/fourslash/codeFixAddMissingMember9.ts b/tests/cases/fourslash/codeFixAddMissingMember9.ts index b583cd28e9a..e22e854c2e5 100644 --- a/tests/cases/fourslash/codeFixAddMissingMember9.ts +++ b/tests/cases/fourslash/codeFixAddMissingMember9.ts @@ -18,7 +18,7 @@ verify.codeFixAll({ const x = 0; this.y(x, "a", this.z); } - y(x: number, arg1: string, z: boolean): any { + y(x: number, arg1: string, z: boolean) { throw new Error("Method not implemented."); } }`, diff --git a/tests/cases/fourslash/codeFixAddMissingMember_all.ts b/tests/cases/fourslash/codeFixAddMissingMember_all.ts index 6c7076dd341..9c0c86f282d 100644 --- a/tests/cases/fourslash/codeFixAddMissingMember_all.ts +++ b/tests/cases/fourslash/codeFixAddMissingMember_all.ts @@ -36,7 +36,7 @@ verify.codeFixAll({ this.y(); this.x = ""; } - y(): any { + y() { throw new Error("Method not implemented."); } } diff --git a/tests/cases/fourslash/codeFixAddMissingMember_generator_function.ts b/tests/cases/fourslash/codeFixAddMissingMember_generator_function.ts index 6742cc43348..ad0bd7b47ca 100644 --- a/tests/cases/fourslash/codeFixAddMissingMember_generator_function.ts +++ b/tests/cases/fourslash/codeFixAddMissingMember_generator_function.ts @@ -14,7 +14,7 @@ verify.codeFixAll({ *method() { yield* this.y(); } - *y(): any { + *y() { throw new Error("Method not implemented."); } }`, diff --git a/tests/cases/fourslash/codeFixAddMissingMember_non_generator_function.ts b/tests/cases/fourslash/codeFixAddMissingMember_non_generator_function.ts index a868646446a..c3773bf285c 100644 --- a/tests/cases/fourslash/codeFixAddMissingMember_non_generator_function.ts +++ b/tests/cases/fourslash/codeFixAddMissingMember_non_generator_function.ts @@ -14,7 +14,7 @@ verify.codeFixAll({ method() { yield* this.y(); } - y(): any { + y() { throw new Error("Method not implemented."); } }`, diff --git a/tests/cases/fourslash/codeFixUndeclaredAcrossFiles1.ts b/tests/cases/fourslash/codeFixUndeclaredAcrossFiles1.ts index 8f775d5158e..a8171668751 100644 --- a/tests/cases/fourslash/codeFixUndeclaredAcrossFiles1.ts +++ b/tests/cases/fourslash/codeFixUndeclaredAcrossFiles1.ts @@ -23,15 +23,15 @@ verify.getAndApplyCodeFix(/*errorCode*/undefined, 0); verify.getAndApplyCodeFix(/*errorCode*/undefined, 0); verify.rangeIs(` - m2(c: C): any { + m2(c: C) { throw new Error("Method not implemented."); } y: {}; - m1(): any { + m1() { throw new Error("Method not implemented."); } static x: any; - static m0(arg0: number, arg1: string, arg2: undefined[]): any { + static m0(arg0: number, arg1: string, arg2: undefined[]) { throw new Error("Method not implemented."); } `); diff --git a/tests/cases/fourslash/codeFixUndeclaredAcrossFiles3.ts b/tests/cases/fourslash/codeFixUndeclaredAcrossFiles3.ts index dcf5c999d6a..9ea5ac1a165 100644 --- a/tests/cases/fourslash/codeFixUndeclaredAcrossFiles3.ts +++ b/tests/cases/fourslash/codeFixUndeclaredAcrossFiles3.ts @@ -20,7 +20,7 @@ verify.getAndApplyCodeFix(/*errorCode*/ undefined, 0); verify.rangeIs(` - m0(arg0: import("./f2").D): any { + m0(arg0: import("./f2").D) { throw new Error("Method not implemented."); } `); \ No newline at end of file diff --git a/tests/cases/fourslash/codeFixUndeclaredInStaticMethod.ts b/tests/cases/fourslash/codeFixUndeclaredInStaticMethod.ts index a406360c500..17fcd9ce688 100644 --- a/tests/cases/fourslash/codeFixUndeclaredInStaticMethod.ts +++ b/tests/cases/fourslash/codeFixUndeclaredInStaticMethod.ts @@ -20,7 +20,7 @@ verify.codeFix({ this.prop1 = 10; A.prop2 = "asdf"; } - static m1(arg0: number, arg1: number, arg2: number): any { + static m1(arg0: number, arg1: number, arg2: number) { throw new Error("Method not implemented."); } }`, @@ -38,10 +38,10 @@ verify.codeFix({ this.prop1 = 10; A.prop2 = "asdf"; } - static m2(arg0: number, arg1: number): any { + static m2(arg0: number, arg1: number) { throw new Error("Method not implemented."); } - static m1(arg0: number, arg1: number, arg2: number): any { + static m1(arg0: number, arg1: number, arg2: number) { throw new Error("Method not implemented."); } }`, @@ -60,10 +60,10 @@ verify.codeFix({ this.prop1 = 10; A.prop2 = "asdf"; } - static m2(arg0: number, arg1: number): any { + static m2(arg0: number, arg1: number) { throw new Error("Method not implemented."); } - static m1(arg0: number, arg1: number, arg2: number): any { + static m1(arg0: number, arg1: number, arg2: number) { throw new Error("Method not implemented."); } }`, @@ -83,10 +83,10 @@ verify.codeFix({ this.prop1 = 10; A.prop2 = "asdf"; } - static m2(arg0: number, arg1: number): any { + static m2(arg0: number, arg1: number) { throw new Error("Method not implemented."); } - static m1(arg0: number, arg1: number, arg2: number): any { + static m1(arg0: number, arg1: number, arg2: number) { throw new Error("Method not implemented."); } }`, diff --git a/tests/cases/fourslash/codeFixUndeclaredMethod.ts b/tests/cases/fourslash/codeFixUndeclaredMethod.ts index 151192078f3..32713e5dd19 100644 --- a/tests/cases/fourslash/codeFixUndeclaredMethod.ts +++ b/tests/cases/fourslash/codeFixUndeclaredMethod.ts @@ -15,7 +15,7 @@ verify.codeFix({ index: 0, newFileContent: `class A { - foo1(arg0: number, arg1: number, arg2: number): any { + foo1(arg0: number, arg1: number, arg2: number) { throw new Error("Method not implemented."); } constructor() { @@ -34,10 +34,10 @@ verify.codeFix({ index: 0, newFileContent: `class A { - foo2(): any { + foo2() { throw new Error("Method not implemented."); } - foo1(arg0: number, arg1: number, arg2: number): any { + foo1(arg0: number, arg1: number, arg2: number) { throw new Error("Method not implemented."); } constructor() { @@ -56,13 +56,13 @@ verify.codeFix({ index: 0, newFileContent: `class A { - foo3(): any { + foo3() { throw new Error("Method not implemented."); } - foo2(): any { + foo2() { throw new Error("Method not implemented."); } - foo1(arg0: number, arg1: number, arg2: number): any { + foo1(arg0: number, arg1: number, arg2: number) { throw new Error("Method not implemented."); } constructor() { diff --git a/tests/cases/fourslash/codeFixUndeclaredMethodFunctionArgs.ts b/tests/cases/fourslash/codeFixUndeclaredMethodFunctionArgs.ts index 478b2a7c647..c4056625b70 100644 --- a/tests/cases/fourslash/codeFixUndeclaredMethodFunctionArgs.ts +++ b/tests/cases/fourslash/codeFixUndeclaredMethodFunctionArgs.ts @@ -11,7 +11,7 @@ verify.codeFix({ description: "Declare method 'foo1'", index: 0, newRangeContent: ` - foo1(arg0: () => number, arg1: () => string, arg2: () => boolean): any { + foo1(arg0: () => number, arg1: () => string, arg2: () => boolean) { throw new Error("Method not implemented."); } `, @@ -22,10 +22,10 @@ verify.codeFix({ description: "Declare method 'foo2'", index: 0, newRangeContent: ` - foo2(arg0: (a: number) => number, arg1: (b: string) => string, arg2: (c: boolean) => boolean): any { + foo2(arg0: (a: number) => number, arg1: (b: string) => string, arg2: (c: boolean) => boolean) { throw new Error("Method not implemented."); } - foo1(arg0: () => number, arg1: () => string, arg2: () => boolean): any { + foo1(arg0: () => number, arg1: () => string, arg2: () => boolean) { throw new Error("Method not implemented."); } `, diff --git a/tests/cases/fourslash/codeFixUndeclaredMethodObjectLiteralArgs.ts b/tests/cases/fourslash/codeFixUndeclaredMethodObjectLiteralArgs.ts index bd434cf9d9d..5c0698ad653 100644 --- a/tests/cases/fourslash/codeFixUndeclaredMethodObjectLiteralArgs.ts +++ b/tests/cases/fourslash/codeFixUndeclaredMethodObjectLiteralArgs.ts @@ -3,6 +3,8 @@ //// class A {[| //// |]constructor() { //// this.foo1(null, {}, { a: 1, b: "2"}); +//// const bar = this.foo2(null, {}, { a: 1, b: "2"}); +//// const baz: number = this.foo3(null, {}, { a: 1, b: "2"}); //// } //// } @@ -10,7 +12,38 @@ verify.codeFix({ description: "Declare method 'foo1'", index: 0, newRangeContent: ` - foo1(arg0: null, arg1: {}, arg2: { a: number; b: string; }): any { + foo1(arg0: null, arg1: {}, arg2: { a: number; b: string; }) { + throw new Error("Method not implemented."); + } + `, + applyChanges: true +}); + +verify.codeFix({ + description: "Declare method 'foo2'", + index: 0, + newRangeContent: ` + foo2(arg0: null, arg1: {}, arg2: { a: number; b: string; }) { + throw new Error("Method not implemented."); + } + foo1(arg0: null, arg1: {}, arg2: { a: number; b: string; }) { + throw new Error("Method not implemented."); + } + `, + applyChanges: true +}); + +verify.codeFix({ + description: "Declare method 'foo3'", + index: 0, + newRangeContent: ` + foo3(arg0: null, arg1: {}, arg2: { a: number; b: string; }): number { + throw new Error("Method not implemented."); + } + foo2(arg0: null, arg1: {}, arg2: { a: number; b: string; }) { + throw new Error("Method not implemented."); + } + foo1(arg0: null, arg1: {}, arg2: { a: number; b: string; }) { throw new Error("Method not implemented."); } ` From d87e67df58bc2b35ace2e3120f12ffee35ddeaf9 Mon Sep 17 00:00:00 2001 From: Joseph Wunderlich Date: Fri, 22 Feb 2019 18:00:21 -0800 Subject: [PATCH 098/149] clarify intent in returnType creation --- src/services/codefixes/helpers.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/services/codefixes/helpers.ts b/src/services/codefixes/helpers.ts index 5f448653a78..45a79613db5 100644 --- a/src/services/codefixes/helpers.ts +++ b/src/services/codefixes/helpers.ts @@ -156,7 +156,7 @@ namespace ts.codefix { isIdentifier(arg) ? arg.text : isPropertyAccessExpression(arg) ? arg.name.text : undefined); const contextualType = checker.getContextualType(call); - const returnType = inJs ? undefined : contextualType && checker.typeToTypeNode(contextualType, contextNode, /*flags*/ undefined, tracker); + const returnType = (inJs || !contextualType) ? undefined : checker.typeToTypeNode(contextualType, contextNode, /*flags*/ undefined, tracker); return createMethod( /*decorators*/ undefined, /*modifiers*/ makeStatic ? [createToken(SyntaxKind.StaticKeyword)] : undefined, From 7a391fe6135b985afe6513d124373b75b41d3210 Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Sun, 24 Feb 2019 23:05:42 -0800 Subject: [PATCH 099/149] Fix `.npmignore` by adding the `.git` file (as opposed to just a directory, which is not the case for git worktrees) and the `.failed-tests` file. --- .npmignore | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.npmignore b/.npmignore index 6054bfbdb37..482633f48fc 100644 --- a/.npmignore +++ b/.npmignore @@ -12,7 +12,11 @@ tests tslint.json Jakefile.js .editorconfig +.failed-tests +.git +.git/ .gitattributes +.github/ .gitmodules .settings/ .travis.yml @@ -23,6 +27,5 @@ Jakefile.js test.config package-lock.json yarn.lock -.github/ CONTRIBUTING.md TEST-results.xml From bc3611d1dd0ba1f899ab824ffe60b64a8b694fa5 Mon Sep 17 00:00:00 2001 From: Gabriela Araujo Britto Date: Mon, 25 Feb 2019 10:32:28 -0800 Subject: [PATCH 100/149] update failing tests --- ...efactorConvertToNamedParameters_callComments2.ts | 13 ++++++------- ...ConvertToNamedParameters_inheritedConstructor.ts | 7 +++++-- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters_callComments2.ts b/tests/cases/fourslash/refactorConvertToNamedParameters_callComments2.ts index 37d4e945a2c..96a56d7024d 100644 --- a/tests/cases/fourslash/refactorConvertToNamedParameters_callComments2.ts +++ b/tests/cases/fourslash/refactorConvertToNamedParameters_callComments2.ts @@ -14,6 +14,7 @@ //// 4); goTo.select("a", "b"); +/* The expected content is currently wrong. The new argument object has the wrong formatting. */ edit.applyRefactor({ refactorName: "Convert to named parameters", actionName: "Convert to named parameters", @@ -22,14 +23,12 @@ edit.applyRefactor({ return a + b; } foo( - { - /**a*/ - a: 1, - /**c*/ - b: 2, - rest: [ + { /**a*/ + a: 1, /**c*/ + b: 2, rest: [ /**e*/ 3, /**g*/ - 4]});` + 4] + });` }); \ No newline at end of file diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters_inheritedConstructor.ts b/tests/cases/fourslash/refactorConvertToNamedParameters_inheritedConstructor.ts index 743fc7fadb4..bde7839a60e 100644 --- a/tests/cases/fourslash/refactorConvertToNamedParameters_inheritedConstructor.ts +++ b/tests/cases/fourslash/refactorConvertToNamedParameters_inheritedConstructor.ts @@ -8,6 +8,9 @@ ////var foo = new Foo("c", "d"); goTo.select("a", "b"); +/* The expected new content is currently wrong. + `new Bar("a", "b")` should be modified by the refactor to be `new Bar({ t: "a", s: "b" })` +*/ edit.applyRefactor({ refactorName: "Convert to named parameters", actionName: "Convert to named parameters", @@ -16,6 +19,6 @@ edit.applyRefactor({ constructor({ t, s }: { t: string; s: string; }) { } } class Bar extends Foo { } -var bar = new Bar({ t: "a", s: "b" }); -var foo = new Foo({ t: "c", s: "d" })` +var bar = new Bar("a", "b"); +var foo = new Foo({ t: "c", s: "d" });` }); \ No newline at end of file From f571866f47cae625918574873f65979e2d4f3850 Mon Sep 17 00:00:00 2001 From: Gabriela Araujo Britto Date: Mon, 25 Feb 2019 10:32:56 -0800 Subject: [PATCH 101/149] add new tests for bad class references --- ...amedParameters_classDeclarationAliasing.ts | 20 ++++++++++++++ ...NamedParameters_classExpressionHeritage.ts | 26 +++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters_classDeclarationAliasing.ts create mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters_classExpressionHeritage.ts diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters_classDeclarationAliasing.ts b/tests/cases/fourslash/refactorConvertToNamedParameters_classDeclarationAliasing.ts new file mode 100644 index 00000000000..0914dedd57d --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToNamedParameters_classDeclarationAliasing.ts @@ -0,0 +1,20 @@ +/// + +////class Foo { +//// /*a*/constructor/*b*/(a: number, b: number) { } +////} +////const fooAlias = Foo; +////const newFoo = new fooAlias(1, 2); + +goTo.select("a", "b"); +// Refactor should not make changes +edit.applyRefactor({ + refactorName: "Convert to named parameters", + actionName: "Convert to named parameters", + actionDescription: "Convert to named parameters", + newContent: `class Foo { + constructor(a: number, b: number) { } +} +const fooAlias = Foo; +const newFoo = new fooAlias(1, 2);` +}); \ No newline at end of file diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters_classExpressionHeritage.ts b/tests/cases/fourslash/refactorConvertToNamedParameters_classExpressionHeritage.ts new file mode 100644 index 00000000000..14b9639c2ad --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToNamedParameters_classExpressionHeritage.ts @@ -0,0 +1,26 @@ +/// + +////const foo = class Foo { +//// /*a*/constructor/*b*/(a: number, b: number) { } +////} +////class Bar extends foo { +//// constructor() { +//// super(1, 2); +//// } +////} + +goTo.select("a", "b"); +// Refactor should not make changes +edit.applyRefactor({ + refactorName: "Convert to named parameters", + actionName: "Convert to named parameters", + actionDescription: "Convert to named parameters", + newContent: `const foo = class Foo { + constructor(a: number, b: number) { } +} +class Bar extends foo { + constructor() { + super(1, 2); + } +}` +}); \ No newline at end of file From a5153a94ab505747c96a4bd0a4704a93796c81a5 Mon Sep 17 00:00:00 2001 From: Gabriela Araujo Britto Date: Mon, 25 Feb 2019 14:14:28 -0800 Subject: [PATCH 102/149] add tests --- ...edParameters_classDeclarationGoodUsages.ts | 31 +++++++++++++++++++ ...medParameters_classExpressionGoodUsages.ts | 23 ++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters_classDeclarationGoodUsages.ts create mode 100644 tests/cases/fourslash/refactorConvertToNamedParameters_classExpressionGoodUsages.ts diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters_classDeclarationGoodUsages.ts b/tests/cases/fourslash/refactorConvertToNamedParameters_classDeclarationGoodUsages.ts new file mode 100644 index 00000000000..858bccd60c1 --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToNamedParameters_classDeclarationGoodUsages.ts @@ -0,0 +1,31 @@ +/// + +////class C { +//// static a: number = 2; +//// /*a*/constructor/*b*/(a: number, b: number) { } +////} +////const newC = new C(1, 2); +////const b = C.a; +////C["a"] = 3; +////let c: C; +////function f(c: C) { } +////class B extends C { } +////class A implements C { } + +goTo.select("a", "b"); +edit.applyRefactor({ + refactorName: "Convert to named parameters", + actionName: "Convert to named parameters", + actionDescription: "Convert to named parameters", + newContent: `class C { + static a: number = 2; + constructor({ a, b }: { a: number; b: number; }) { } +} +const newC = new C({ a: 1, b: 2 }); +const b = C.a; +C["a"] = 3; +let c: C; +function f(c: C) { } +class B extends C { } +class A implements C { }` +}); \ No newline at end of file diff --git a/tests/cases/fourslash/refactorConvertToNamedParameters_classExpressionGoodUsages.ts b/tests/cases/fourslash/refactorConvertToNamedParameters_classExpressionGoodUsages.ts new file mode 100644 index 00000000000..f8023b9898c --- /dev/null +++ b/tests/cases/fourslash/refactorConvertToNamedParameters_classExpressionGoodUsages.ts @@ -0,0 +1,23 @@ +/// + +////const c = class C { +//// static a: number = 2; +//// /*a*/constructor/*b*/(a: number, b: number) { } +////} +////const a = new c(0, 1); +////const b = c.a; +////c["a"] = 3; + +goTo.select("a", "b"); +edit.applyRefactor({ + refactorName: "Convert to named parameters", + actionName: "Convert to named parameters", + actionDescription: "Convert to named parameters", + newContent: `const c = class C { + static a: number = 2; + constructor({ a, b }: { a: number; b: number; }) { } +} +const a = new c({ a: 0, b: 1 }); +const b = c.a; +c["a"] = 3;` +}); \ No newline at end of file From c2f19983876c94035d5ff4f1a4c37c0999d08bed Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Mon, 25 Feb 2019 16:18:03 -0800 Subject: [PATCH 103/149] Fix baseline accept when there are multiple .delete files (#30091) --- scripts/build/utils.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/scripts/build/utils.js b/scripts/build/utils.js index f9e48c58256..b070bd133a9 100644 --- a/scripts/build/utils.js +++ b/scripts/build/utils.js @@ -340,7 +340,6 @@ function rm(dest, opts) { duplex.push(file); cb(); } - duplex.push(null); // signal end of read queue }; const duplex = new Duplex({ @@ -374,15 +373,16 @@ function rm(dest, opts) { pending.push(entry); }, final(cb) { + const endThenCb = () => (duplex.push(null), cb()); // signal end of read queue processDeleted(); if (pending.length) { Promise .all(pending.map(entry => entry.promise)) .then(() => processDeleted()) - .then(() => cb(), cb); + .then(() => endThenCb(), endThenCb); return; } - cb(); + endThenCb(); }, read() { } From 0e858a6e16e04703900ce2aef4713bb6b64eef21 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Mon, 25 Feb 2019 16:33:20 -0800 Subject: [PATCH 104/149] Include misc script outputs in local build (#30092) * Include other misc script outputs in local build * Remove comment --- Gulpfile.js | 51 +++++++++++++++++++++++++++------------------------ 1 file changed, 27 insertions(+), 24 deletions(-) diff --git a/Gulpfile.js b/Gulpfile.js index 93770f9d498..3ce488caedd 100644 --- a/Gulpfile.js +++ b/Gulpfile.js @@ -373,9 +373,34 @@ task("lint").flags = { " --f[iles]=": "pattern to match files to lint", }; +const buildCancellationToken = () => buildProject("src/cancellationToken"); +const cleanCancellationToken = () => cleanProject("src/cancellationToken"); +cleanTasks.push(cleanCancellationToken); + +const buildTypingsInstaller = () => buildProject("src/typingsInstaller"); +const cleanTypingsInstaller = () => cleanProject("src/typingsInstaller"); +cleanTasks.push(cleanTypingsInstaller); + +const buildWatchGuard = () => buildProject("src/watchGuard"); +const cleanWatchGuard = () => cleanProject("src/watchGuard"); +cleanTasks.push(cleanWatchGuard); + +const generateTypesMap = () => src("src/server/typesMap.json") + .pipe(newer("built/local/typesMap.json")) + .pipe(transform(contents => (JSON.parse(contents), contents))) // validates typesMap.json is valid JSON + .pipe(dest("built/local")); +task("generate-types-map", generateTypesMap); + +const cleanTypesMap = () => del("built/local/typesMap.json"); +cleanTasks.push(cleanTypesMap); + +const buildOtherOutputs = parallel(buildCancellationToken, buildTypingsInstaller, buildWatchGuard, generateTypesMap); +task("other-outputs", series(preBuild, buildOtherOutputs)); +task("other-outputs").description = "Builds miscelaneous scripts and documents distributed with the LKG"; + const buildFoldStart = async () => { if (fold.isTravis()) console.log(fold.start("build")); }; const buildFoldEnd = async () => { if (fold.isTravis()) console.log(fold.end("build")); }; -task("local", series(buildFoldStart, preBuild, parallel(localize, buildTsc, buildServer, buildServices, buildLssl), buildFoldEnd)); +task("local", series(buildFoldStart, preBuild, parallel(localize, buildTsc, buildServer, buildServices, buildLssl, buildOtherOutputs), buildFoldEnd)); task("local").description = "Builds the full compiler and services"; task("local").flags = { " --built": "Compile using the built version of the compiler." @@ -551,28 +576,6 @@ const buildReleaseTsc = () => buildProject("src/tsc/tsconfig.release.json"); const cleanReleaseTsc = () => cleanProject("src/tsc/tsconfig.release.json"); cleanTasks.push(cleanReleaseTsc); -const buildCancellationToken = () => buildProject("src/cancellationToken"); -const cleanCancellationToken = () => cleanProject("src/cancellationToken"); -cleanTasks.push(cleanCancellationToken); - -const buildTypingsInstaller = () => buildProject("src/typingsInstaller"); -const cleanTypingsInstaller = () => cleanProject("src/typingsInstaller"); -cleanTasks.push(cleanTypingsInstaller); - -const buildWatchGuard = () => buildProject("src/watchGuard"); -const cleanWatchGuard = () => cleanProject("src/watchGuard"); -cleanTasks.push(cleanWatchGuard); - -// TODO(rbuckton): This task isn't triggered by any other task. Is it still needed? -const generateTypesMap = () => src("src/server/typesMap.json") - .pipe(newer("built/local/typesMap.json")) - .pipe(transform(contents => (JSON.parse(contents), contents))) // validates typesMap.json is valid JSON - .pipe(dest("built/local")); -task("generate-types-map", generateTypesMap); - -const cleanTypesMap = () => del("built/local/typesMap.json"); -cleanTasks.push(cleanTypesMap); - const cleanBuilt = () => del("built"); const produceLKG = async () => { @@ -602,7 +605,7 @@ const produceLKG = async () => { } }; -task("LKG", series(lkgPreBuild, parallel(localize, buildTsc, buildServer, buildServices, buildLssl, buildCancellationToken, buildTypingsInstaller, buildWatchGuard, buildReleaseTsc), produceLKG)); +task("LKG", series(lkgPreBuild, parallel(localize, buildTsc, buildServer, buildServices, buildLssl, buildOtherOutputs, buildReleaseTsc), produceLKG)); task("LKG").description = "Makes a new LKG out of the built js files"; task("LKG").flags = { " --built": "Compile using the built version of the compiler.", From c5061486a9ea1694af249c6e9d434d7166bd26bd Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Mon, 25 Feb 2019 17:10:03 -0800 Subject: [PATCH 105/149] Retain substitution types through instantiation if possible (#30059) --- src/compiler/checker.ts | 11 ++- ...dAliasAssignableToConstraintSameAsAlias.js | 36 ++++++++ ...sAssignableToConstraintSameAsAlias.symbols | 85 +++++++++++++++++++ ...iasAssignableToConstraintSameAsAlias.types | 45 ++++++++++ ...dAliasAssignableToConstraintSameAsAlias.ts | 24 ++++++ 5 files changed, 200 insertions(+), 1 deletion(-) create mode 100644 tests/baselines/reference/inlinedAliasAssignableToConstraintSameAsAlias.js create mode 100644 tests/baselines/reference/inlinedAliasAssignableToConstraintSameAsAlias.symbols create mode 100644 tests/baselines/reference/inlinedAliasAssignableToConstraintSameAsAlias.types create mode 100644 tests/cases/compiler/inlinedAliasAssignableToConstraintSameAsAlias.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 958ceae0395..ddc958df0b4 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -11062,7 +11062,13 @@ namespace ts { return getConditionalTypeInstantiation(type, combineTypeMappers((type).mapper, mapper)); } if (flags & TypeFlags.Substitution) { - return instantiateType((type).typeVariable, mapper); + const maybeVariable = instantiateType((type).typeVariable, mapper); + if (maybeVariable.flags & TypeFlags.TypeVariable) { + return getSubstitutionType(maybeVariable as TypeVariable, instantiateType((type).substitute, mapper)); + } + else { + return maybeVariable; + } } return type; } @@ -14465,6 +14471,9 @@ namespace ts { } } } + else if (target.flags & TypeFlags.Substitution) { + inferFromTypes(source, (target as SubstitutionType).typeVariable); + } if (getObjectFlags(source) & ObjectFlags.Reference && getObjectFlags(target) & ObjectFlags.Reference && (source).target === (target).target) { // If source and target are references to the same generic type, infer from type arguments const sourceTypes = (source).typeArguments || emptyArray; diff --git a/tests/baselines/reference/inlinedAliasAssignableToConstraintSameAsAlias.js b/tests/baselines/reference/inlinedAliasAssignableToConstraintSameAsAlias.js new file mode 100644 index 00000000000..2d82034c6f7 --- /dev/null +++ b/tests/baselines/reference/inlinedAliasAssignableToConstraintSameAsAlias.js @@ -0,0 +1,36 @@ +//// [inlinedAliasAssignableToConstraintSameAsAlias.ts] +interface RelationFields { + x: A; + y: A[]; + z: A[]; +} +type Name = keyof RelationFields; +type ShouldA = RF[N] extends A[] + ? RF[N][0] + : never; + +class A { + x: A; + y: A[]; + z: A[]; + + whereRelated< // Works // Type is same as A1, but is not assignable to type A + RF extends RelationFields = RelationFields, + N extends Name = Name, + A1 extends A = RF[N] extends A[] ? RF[N][0] : never, + A2 extends A = ShouldA + >(): number { + return 1; + } +} + + +//// [inlinedAliasAssignableToConstraintSameAsAlias.js] +var A = /** @class */ (function () { + function A() { + } + A.prototype.whereRelated = function () { + return 1; + }; + return A; +}()); diff --git a/tests/baselines/reference/inlinedAliasAssignableToConstraintSameAsAlias.symbols b/tests/baselines/reference/inlinedAliasAssignableToConstraintSameAsAlias.symbols new file mode 100644 index 00000000000..86e55f14ee9 --- /dev/null +++ b/tests/baselines/reference/inlinedAliasAssignableToConstraintSameAsAlias.symbols @@ -0,0 +1,85 @@ +=== tests/cases/compiler/inlinedAliasAssignableToConstraintSameAsAlias.ts === +interface RelationFields { +>RelationFields : Symbol(RelationFields, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 0, 0)) + + x: A; +>x : Symbol(RelationFields.x, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 0, 26)) +>A : Symbol(A, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 8, 10)) + + y: A[]; +>y : Symbol(RelationFields.y, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 1, 7)) +>A : Symbol(A, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 8, 10)) + + z: A[]; +>z : Symbol(RelationFields.z, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 2, 9)) +>A : Symbol(A, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 8, 10)) +} +type Name = keyof RelationFields; +>Name : Symbol(Name, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 4, 1)) +>RelationFields : Symbol(RelationFields, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 0, 0)) + +type ShouldA = RF[N] extends A[] +>ShouldA : Symbol(ShouldA, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 5, 33)) +>RF : Symbol(RF, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 6, 13)) +>RelationFields : Symbol(RelationFields, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 0, 0)) +>N : Symbol(N, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 6, 39)) +>Name : Symbol(Name, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 4, 1)) +>RF : Symbol(RF, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 6, 13)) +>N : Symbol(N, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 6, 39)) +>A : Symbol(A, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 8, 10)) + + ? RF[N][0] +>RF : Symbol(RF, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 6, 13)) +>N : Symbol(N, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 6, 39)) + + : never; + +class A { +>A : Symbol(A, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 8, 10)) + + x: A; +>x : Symbol(A.x, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 10, 9)) +>A : Symbol(A, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 8, 10)) + + y: A[]; +>y : Symbol(A.y, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 11, 7)) +>A : Symbol(A, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 8, 10)) + + z: A[]; +>z : Symbol(A.z, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 12, 9)) +>A : Symbol(A, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 8, 10)) + + whereRelated< // Works // Type is same as A1, but is not assignable to type A +>whereRelated : Symbol(A.whereRelated, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 13, 9)) + + RF extends RelationFields = RelationFields, +>RF : Symbol(RF, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 15, 15)) +>RelationFields : Symbol(RelationFields, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 0, 0)) +>RelationFields : Symbol(RelationFields, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 0, 0)) + + N extends Name = Name, +>N : Symbol(N, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 16, 47)) +>Name : Symbol(Name, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 4, 1)) +>Name : Symbol(Name, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 4, 1)) + + A1 extends A = RF[N] extends A[] ? RF[N][0] : never, +>A1 : Symbol(A1, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 17, 26)) +>A : Symbol(A, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 8, 10)) +>RF : Symbol(RF, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 15, 15)) +>N : Symbol(N, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 16, 47)) +>A : Symbol(A, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 8, 10)) +>RF : Symbol(RF, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 15, 15)) +>N : Symbol(N, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 16, 47)) + + A2 extends A = ShouldA +>A2 : Symbol(A2, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 18, 56)) +>A : Symbol(A, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 8, 10)) +>ShouldA : Symbol(ShouldA, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 5, 33)) +>RF : Symbol(RF, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 15, 15)) +>N : Symbol(N, Decl(inlinedAliasAssignableToConstraintSameAsAlias.ts, 16, 47)) + + >(): number { + return 1; + } +} + diff --git a/tests/baselines/reference/inlinedAliasAssignableToConstraintSameAsAlias.types b/tests/baselines/reference/inlinedAliasAssignableToConstraintSameAsAlias.types new file mode 100644 index 00000000000..d337fbc718a --- /dev/null +++ b/tests/baselines/reference/inlinedAliasAssignableToConstraintSameAsAlias.types @@ -0,0 +1,45 @@ +=== tests/cases/compiler/inlinedAliasAssignableToConstraintSameAsAlias.ts === +interface RelationFields { + x: A; +>x : A + + y: A[]; +>y : A[] + + z: A[]; +>z : A[] +} +type Name = keyof RelationFields; +>Name : "x" | "y" | "z" + +type ShouldA = RF[N] extends A[] +>ShouldA : ShouldA + + ? RF[N][0] + : never; + +class A { +>A : A + + x: A; +>x : A + + y: A[]; +>y : A[] + + z: A[]; +>z : A[] + + whereRelated< // Works // Type is same as A1, but is not assignable to type A +>whereRelated : >() => number + + RF extends RelationFields = RelationFields, + N extends Name = Name, + A1 extends A = RF[N] extends A[] ? RF[N][0] : never, + A2 extends A = ShouldA + >(): number { + return 1; +>1 : 1 + } +} + diff --git a/tests/cases/compiler/inlinedAliasAssignableToConstraintSameAsAlias.ts b/tests/cases/compiler/inlinedAliasAssignableToConstraintSameAsAlias.ts new file mode 100644 index 00000000000..165ec0dc17e --- /dev/null +++ b/tests/cases/compiler/inlinedAliasAssignableToConstraintSameAsAlias.ts @@ -0,0 +1,24 @@ +interface RelationFields { + x: A; + y: A[]; + z: A[]; +} +type Name = keyof RelationFields; +type ShouldA = RF[N] extends A[] + ? RF[N][0] + : never; + +class A { + x: A; + y: A[]; + z: A[]; + + whereRelated< // Works // Type is same as A1, but is not assignable to type A + RF extends RelationFields = RelationFields, + N extends Name = Name, + A1 extends A = RF[N] extends A[] ? RF[N][0] : never, + A2 extends A = ShouldA + >(): number { + return 1; + } +} From 4d7ec380a9a5d6f7e2f882d6bae9557d7414afb5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E6=96=87=E7=92=90?= Date: Tue, 26 Feb 2019 10:54:01 +0800 Subject: [PATCH 106/149] check completions with assignable rather than identity --- src/compiler/checker.ts | 2 +- .../completionsWithOptionalProperties.ts | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 tests/cases/fourslash/completionsWithOptionalProperties.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index ddc958df0b4..c882227ba0c 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -7406,7 +7406,7 @@ namespace ts { const nameType = property.name && getLiteralTypeFromPropertyName(property.name); const name = nameType && isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : undefined; const expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name); - return !!expected && isLiteralType(expected) && !isTypeIdenticalTo(getTypeOfNode(property), expected); + return !!expected && isLiteralType(expected) && !isTypeAssignableTo(getTypeOfNode(property), expected); }); } diff --git a/tests/cases/fourslash/completionsWithOptionalProperties.ts b/tests/cases/fourslash/completionsWithOptionalProperties.ts new file mode 100644 index 00000000000..e40029ddefa --- /dev/null +++ b/tests/cases/fourslash/completionsWithOptionalProperties.ts @@ -0,0 +1,18 @@ +/// +// @strict: true + +//// interface Options { +//// hello?: boolean; +//// world?: boolean; +//// } +//// declare function foo(options?: Options): void; +//// foo({ +//// hello: true, +//// /**/ +//// }); + +verify.completions({ + marker: "", + includes: ['world'] +}); + From 1ed5e1c63b71e0a4e7fd0493a37e43a7ef518ebb Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Mon, 25 Feb 2019 19:50:53 -0800 Subject: [PATCH 107/149] Do not wrap npm path with quotes Fixes #30086 --- src/typingsInstaller/nodeTypingsInstaller.ts | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/typingsInstaller/nodeTypingsInstaller.ts b/src/typingsInstaller/nodeTypingsInstaller.ts index 1d75218c883..2facb1223d0 100644 --- a/src/typingsInstaller/nodeTypingsInstaller.ts +++ b/src/typingsInstaller/nodeTypingsInstaller.ts @@ -89,10 +89,6 @@ namespace ts.server.typingsInstaller { log); this.npmPath = npmLocation !== undefined ? npmLocation : getDefaultNPMLocation(process.argv[0]); - // If the NPM path contains spaces and isn't wrapped in quotes, do so. - if (stringContains(this.npmPath, " ") && this.npmPath[0] !== `"`) { - this.npmPath = `"${this.npmPath}"`; - } if (this.log.isEnabled()) { this.log.writeLine(`Process id: ${process.pid}`); this.log.writeLine(`NPM location: ${this.npmPath} (explicit '${Arguments.NpmLocation}' ${npmLocation === undefined ? "not " : ""} provided)`); From e3a465ffa3136e2676cf2af1ac978c8e814b7b74 Mon Sep 17 00:00:00 2001 From: Gabriela Araujo Britto Date: Tue, 26 Feb 2019 09:43:35 -0800 Subject: [PATCH 108/149] change startPosition and endPosition to leadingTriviaOption and trailingTriviaOption --- src/services/organizeImports.ts | 4 +-- .../refactors/convertToNamedParameters.ts | 6 ++-- src/services/textChanges.ts | 35 +++++++++---------- .../unittests/services/textChanges.ts | 26 +++++++------- 4 files changed, 35 insertions(+), 36 deletions(-) diff --git a/src/services/organizeImports.ts b/src/services/organizeImports.ts index 8096ffa4ad2..5bfa0c74ab1 100644 --- a/src/services/organizeImports.ts +++ b/src/services/organizeImports.ts @@ -68,8 +68,8 @@ namespace ts.OrganizeImports { else { // Note: Delete the surrounding trivia because it will have been retained in newImportDecls. changeTracker.replaceNodeWithNodes(sourceFile, oldImportDecls[0], newImportDecls, { - startPosition: textChanges.LeadingTriviaOption.Exclude, // Leave header comment in place - endPosition: textChanges.TrailingTriviaOption.Include, + leadingTriviaOption: textChanges.LeadingTriviaOption.Exclude, // Leave header comment in place + trailingTriviaOption: textChanges.TrailingTriviaOption.Include, suffix: getNewLineOrDefaultFromHost(host, formatContext.options), }); } diff --git a/src/services/refactors/convertToNamedParameters.ts b/src/services/refactors/convertToNamedParameters.ts index 9bcea0e5983..fa285619dab 100644 --- a/src/services/refactors/convertToNamedParameters.ts +++ b/src/services/refactors/convertToNamedParameters.ts @@ -50,8 +50,8 @@ namespace ts.refactor.convertToNamedParameters { { joiner: ", ", // indentation is set to 0 because otherwise the object parameter will be indented if there is a `this` parameter indentation: 0, - startPosition: textChanges.LeadingTriviaOption.IncludeAll, - endPosition: textChanges.TrailingTriviaOption.Include + leadingTriviaOption: textChanges.LeadingTriviaOption.IncludeAll, + trailingTriviaOption: textChanges.TrailingTriviaOption.Include }); @@ -64,7 +64,7 @@ namespace ts.refactor.convertToNamedParameters { first(call.arguments), last(call.arguments), newArgument, - { startPosition: textChanges.LeadingTriviaOption.IncludeAll, endPosition: textChanges.TrailingTriviaOption.Include }); + { leadingTriviaOption: textChanges.LeadingTriviaOption.IncludeAll, trailingTriviaOption: textChanges.TrailingTriviaOption.Include }); }}); } diff --git a/src/services/textChanges.ts b/src/services/textChanges.ts index b8e8ee90ee9..529fcef51de 100644 --- a/src/services/textChanges.ts +++ b/src/services/textChanges.ts @@ -28,11 +28,10 @@ namespace ts.textChanges { } export interface ConfigurableStart { - startPosition?: LeadingTriviaOption; + leadingTriviaOption?: LeadingTriviaOption; } export interface ConfigurableEnd { - /** True to use getEnd() without adjustment. */ - endPosition?: TrailingTriviaOption; + trailingTriviaOption?: TrailingTriviaOption; } export enum LeadingTriviaOption { @@ -48,7 +47,7 @@ namespace ts.textChanges { } export enum TrailingTriviaOption { - /** Exclude all leading trivia (use getEnd()) */ + /** Exclude all trailing trivia (use getEnd()) */ Exclude, /** TODO (default behavior) */ IncludeIfLineBreak, @@ -88,8 +87,8 @@ namespace ts.textChanges { export interface ConfigurableStartEnd extends ConfigurableStart, ConfigurableEnd {} export const useNonAdjustedPositions: ConfigurableStartEnd = { - startPosition: LeadingTriviaOption.Exclude, - endPosition: TrailingTriviaOption.Exclude, + leadingTriviaOption: LeadingTriviaOption.Exclude, + trailingTriviaOption: TrailingTriviaOption.Exclude, }; export interface InsertNodeOptions { @@ -162,8 +161,8 @@ namespace ts.textChanges { } function getAdjustedStartPosition(sourceFile: SourceFile, node: Node, options: ConfigurableStart) { - const { startPosition } = options; - if (startPosition === LeadingTriviaOption.Exclude) { + const { leadingTriviaOption } = options; + if (leadingTriviaOption === LeadingTriviaOption.Exclude) { return node.getStart(sourceFile); } const fullStart = node.getFullStart(); @@ -181,7 +180,7 @@ namespace ts.textChanges { // fullstart // when b is replaced - we usually want to keep the leading trvia // when b is deleted - we delete it - return startPosition === LeadingTriviaOption.IncludeAll ? fullStart : start; + return leadingTriviaOption === LeadingTriviaOption.IncludeAll ? fullStart : start; } // get start position of the line following the line that contains fullstart position // (but only if the fullstart isn't the very beginning of the file) @@ -194,12 +193,12 @@ namespace ts.textChanges { function getAdjustedEndPosition(sourceFile: SourceFile, node: Node, options: ConfigurableEnd) { const { end } = node; - const { endPosition } = options; - if (endPosition === TrailingTriviaOption.Exclude || (isExpression(node) && endPosition !== TrailingTriviaOption.Include)) { + const { trailingTriviaOption } = options; + if (trailingTriviaOption === TrailingTriviaOption.Exclude || (isExpression(node) && trailingTriviaOption !== TrailingTriviaOption.Include)) { return end; } const newEnd = skipTrivia(sourceFile.text, end, /*stopAfterLineBreak*/ true); - return newEnd !== end && (endPosition === TrailingTriviaOption.Include || isLineBreak(sourceFile.text.charCodeAt(newEnd - 1))) + return newEnd !== end && (trailingTriviaOption === TrailingTriviaOption.Include || isLineBreak(sourceFile.text.charCodeAt(newEnd - 1))) ? newEnd : end; } @@ -257,13 +256,13 @@ namespace ts.textChanges { this.deleteRange(sourceFile, { pos: modifier.getStart(sourceFile), end: skipTrivia(sourceFile.text, modifier.end, /*stopAfterLineBreak*/ true) }); } - public deleteNodeRange(sourceFile: SourceFile, startNode: Node, endNode: Node, options: ConfigurableStartEnd = { startPosition: LeadingTriviaOption.IncludeAll }): void { + public deleteNodeRange(sourceFile: SourceFile, startNode: Node, endNode: Node, options: ConfigurableStartEnd = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }): void { const startPosition = getAdjustedStartPosition(sourceFile, startNode, options); const endPosition = getAdjustedEndPosition(sourceFile, endNode, options); this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); } - public deleteNodeRangeExcludingEnd(sourceFile: SourceFile, startNode: Node, afterEndNode: Node | undefined, options: ConfigurableStartEnd = { startPosition: LeadingTriviaOption.IncludeAll }): void { + public deleteNodeRangeExcludingEnd(sourceFile: SourceFile, startNode: Node, afterEndNode: Node | undefined, options: ConfigurableStartEnd = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }): void { const startPosition = getAdjustedStartPosition(sourceFile, startNode, options); const endPosition = afterEndNode === undefined ? sourceFile.text.length : getAdjustedStartPosition(sourceFile, afterEndNode, options); this.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); @@ -753,7 +752,7 @@ namespace ts.textChanges { // find first non-whitespace position in the leading trivia of the node function startPositionToDeleteNodeInList(sourceFile: SourceFile, node: Node): number { - return skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, { startPosition: LeadingTriviaOption.IncludeAll }), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); + return skipTrivia(sourceFile.text, getAdjustedStartPosition(sourceFile, node, { leadingTriviaOption: LeadingTriviaOption.IncludeAll }), /*stopAfterLineBreak*/ false, /*stopAtComments*/ true); } function getClassOrObjectBraceEnds(cls: ClassLikeDeclaration | InterfaceDeclaration | ObjectLiteralExpression, sourceFile: SourceFile): [number, number] { @@ -1107,7 +1106,7 @@ namespace ts.textChanges { case SyntaxKind.ImportDeclaration: deleteNode(changes, sourceFile, node, // For first import, leave header comment in place - node === sourceFile.imports[0].parent ? { startPosition: LeadingTriviaOption.Exclude, endPosition: TrailingTriviaOption.IncludeIfLineBreak } : undefined); + node === sourceFile.imports[0].parent ? { leadingTriviaOption: LeadingTriviaOption.Exclude, trailingTriviaOption: TrailingTriviaOption.IncludeIfLineBreak } : undefined); break; case SyntaxKind.BindingElement: @@ -1151,7 +1150,7 @@ namespace ts.textChanges { deleteNodeInList(changes, deletedNodesInLists, sourceFile, node); } else { - deleteNode(changes, sourceFile, node, node.kind === SyntaxKind.SemicolonToken ? { endPosition: TrailingTriviaOption.Exclude } : undefined); + deleteNode(changes, sourceFile, node, node.kind === SyntaxKind.SemicolonToken ? { trailingTriviaOption: TrailingTriviaOption.Exclude } : undefined); } } } @@ -1230,7 +1229,7 @@ namespace ts.textChanges { /** Warning: This deletes comments too. See `copyComments` in `convertFunctionToEs6Class`. */ // Exported for tests only! (TODO: improve tests to not need this) - export function deleteNode(changes: ChangeTracker, sourceFile: SourceFile, node: Node, options: ConfigurableStartEnd = { startPosition: LeadingTriviaOption.IncludeAll }): void { + export function deleteNode(changes: ChangeTracker, sourceFile: SourceFile, node: Node, options: ConfigurableStartEnd = { leadingTriviaOption: LeadingTriviaOption.IncludeAll }): void { const startPosition = getAdjustedStartPosition(sourceFile, node, options); const endPosition = getAdjustedEndPosition(sourceFile, node, options); changes.deleteRange(sourceFile, { pos: startPosition, end: endPosition }); diff --git a/src/testRunner/unittests/services/textChanges.ts b/src/testRunner/unittests/services/textChanges.ts index f9e03a578de..27195c30034 100644 --- a/src/testRunner/unittests/services/textChanges.ts +++ b/src/testRunner/unittests/services/textChanges.ts @@ -140,13 +140,13 @@ var z = 3; // comment 4 deleteNode(changeTracker, sourceFile, findVariableStatementContaining("y", sourceFile)); }); runSingleFileTest("deleteNode2", /*placeOpenBraceOnNewLineForFunctions*/ false, text, /*validateNodes*/ false, (sourceFile, changeTracker) => { - deleteNode(changeTracker, sourceFile, findVariableStatementContaining("y", sourceFile), { startPosition: textChanges.LeadingTriviaOption.Exclude }); + deleteNode(changeTracker, sourceFile, findVariableStatementContaining("y", sourceFile), { leadingTriviaOption: textChanges.LeadingTriviaOption.Exclude }); }); runSingleFileTest("deleteNode3", /*placeOpenBraceOnNewLineForFunctions*/ false, text, /*validateNodes*/ false, (sourceFile, changeTracker) => { - deleteNode(changeTracker, sourceFile, findVariableStatementContaining("y", sourceFile), { endPosition: textChanges.TrailingTriviaOption.Exclude }); + deleteNode(changeTracker, sourceFile, findVariableStatementContaining("y", sourceFile), { trailingTriviaOption: textChanges.TrailingTriviaOption.Exclude }); }); runSingleFileTest("deleteNode4", /*placeOpenBraceOnNewLineForFunctions*/ false, text, /*validateNodes*/ false, (sourceFile, changeTracker) => { - deleteNode(changeTracker, sourceFile, findVariableStatementContaining("y", sourceFile), { startPosition: textChanges.LeadingTriviaOption.Exclude, endPosition: textChanges.TrailingTriviaOption.Exclude }); + deleteNode(changeTracker, sourceFile, findVariableStatementContaining("y", sourceFile), { leadingTriviaOption: textChanges.LeadingTriviaOption.Exclude, trailingTriviaOption: textChanges.TrailingTriviaOption.Exclude }); }); runSingleFileTest("deleteNode5", /*placeOpenBraceOnNewLineForFunctions*/ false, text, /*validateNodes*/ false, (sourceFile, changeTracker) => { deleteNode(changeTracker, sourceFile, findVariableStatementContaining("x", sourceFile)); @@ -167,15 +167,15 @@ var a = 4; // comment 7 }); runSingleFileTest("deleteNodeRange2", /*placeOpenBraceOnNewLineForFunctions*/ false, text, /*validateNodes*/ false, (sourceFile, changeTracker) => { changeTracker.deleteNodeRange(sourceFile, findVariableStatementContaining("y", sourceFile), findVariableStatementContaining("z", sourceFile), - { startPosition: textChanges.LeadingTriviaOption.Exclude }); + { leadingTriviaOption: textChanges.LeadingTriviaOption.Exclude }); }); runSingleFileTest("deleteNodeRange3", /*placeOpenBraceOnNewLineForFunctions*/ false, text, /*validateNodes*/ false, (sourceFile, changeTracker) => { changeTracker.deleteNodeRange(sourceFile, findVariableStatementContaining("y", sourceFile), findVariableStatementContaining("z", sourceFile), - { endPosition: textChanges.TrailingTriviaOption.Exclude }); + { trailingTriviaOption: textChanges.TrailingTriviaOption.Exclude }); }); runSingleFileTest("deleteNodeRange4", /*placeOpenBraceOnNewLineForFunctions*/ false, text, /*validateNodes*/ false, (sourceFile, changeTracker) => { changeTracker.deleteNodeRange(sourceFile, findVariableStatementContaining("y", sourceFile), findVariableStatementContaining("z", sourceFile), - { startPosition: textChanges.LeadingTriviaOption.Exclude, endPosition: textChanges.TrailingTriviaOption.Exclude }); + { leadingTriviaOption: textChanges.LeadingTriviaOption.Exclude, trailingTriviaOption: textChanges.TrailingTriviaOption.Exclude }); }); } function createTestVariableDeclaration(name: string) { @@ -254,16 +254,16 @@ var a = 4; // comment 7`; changeTracker.replaceNode(sourceFile, findVariableStatementContaining("y", sourceFile), createTestClass(), { suffix: newLineCharacter }); }); runSingleFileTest("replaceNode2", /*placeOpenBraceOnNewLineForFunctions*/ true, text, /*validateNodes*/ true, (sourceFile, changeTracker) => { - changeTracker.replaceNode(sourceFile, findVariableStatementContaining("y", sourceFile), createTestClass(), { startPosition: textChanges.LeadingTriviaOption.Exclude, suffix: newLineCharacter, prefix: newLineCharacter }); + changeTracker.replaceNode(sourceFile, findVariableStatementContaining("y", sourceFile), createTestClass(), { leadingTriviaOption: textChanges.LeadingTriviaOption.Exclude, suffix: newLineCharacter, prefix: newLineCharacter }); }); runSingleFileTest("replaceNode3", /*placeOpenBraceOnNewLineForFunctions*/ true, text, /*validateNodes*/ true, (sourceFile, changeTracker) => { - changeTracker.replaceNode(sourceFile, findVariableStatementContaining("y", sourceFile), createTestClass(), { endPosition: textChanges.TrailingTriviaOption.Exclude, suffix: newLineCharacter }); + changeTracker.replaceNode(sourceFile, findVariableStatementContaining("y", sourceFile), createTestClass(), { trailingTriviaOption: textChanges.TrailingTriviaOption.Exclude, suffix: newLineCharacter }); }); runSingleFileTest("replaceNode4", /*placeOpenBraceOnNewLineForFunctions*/ true, text, /*validateNodes*/ true, (sourceFile, changeTracker) => { - changeTracker.replaceNode(sourceFile, findVariableStatementContaining("y", sourceFile), createTestClass(), { startPosition: textChanges.LeadingTriviaOption.Exclude, endPosition: textChanges.TrailingTriviaOption.Exclude }); + changeTracker.replaceNode(sourceFile, findVariableStatementContaining("y", sourceFile), createTestClass(), { leadingTriviaOption: textChanges.LeadingTriviaOption.Exclude, trailingTriviaOption: textChanges.TrailingTriviaOption.Exclude }); }); runSingleFileTest("replaceNode5", /*placeOpenBraceOnNewLineForFunctions*/ true, text, /*validateNodes*/ true, (sourceFile, changeTracker) => { - changeTracker.replaceNode(sourceFile, findVariableStatementContaining("x", sourceFile), createTestClass(), { startPosition: textChanges.LeadingTriviaOption.Exclude, endPosition: textChanges.TrailingTriviaOption.Exclude }); + changeTracker.replaceNode(sourceFile, findVariableStatementContaining("x", sourceFile), createTestClass(), { leadingTriviaOption: textChanges.LeadingTriviaOption.Exclude, trailingTriviaOption: textChanges.TrailingTriviaOption.Exclude }); }); } { @@ -279,13 +279,13 @@ var a = 4; // comment 7`; changeTracker.replaceNodeRange(sourceFile, findVariableStatementContaining("y", sourceFile), findVariableStatementContaining("z", sourceFile), createTestClass(), { suffix: newLineCharacter }); }); runSingleFileTest("replaceNodeRange2", /*placeOpenBraceOnNewLineForFunctions*/ true, text, /*validateNodes*/ true, (sourceFile, changeTracker) => { - changeTracker.replaceNodeRange(sourceFile, findVariableStatementContaining("y", sourceFile), findVariableStatementContaining("z", sourceFile), createTestClass(), { startPosition: textChanges.LeadingTriviaOption.Exclude, suffix: newLineCharacter, prefix: newLineCharacter }); + changeTracker.replaceNodeRange(sourceFile, findVariableStatementContaining("y", sourceFile), findVariableStatementContaining("z", sourceFile), createTestClass(), { leadingTriviaOption: textChanges.LeadingTriviaOption.Exclude, suffix: newLineCharacter, prefix: newLineCharacter }); }); runSingleFileTest("replaceNodeRange3", /*placeOpenBraceOnNewLineForFunctions*/ true, text, /*validateNodes*/ true, (sourceFile, changeTracker) => { - changeTracker.replaceNodeRange(sourceFile, findVariableStatementContaining("y", sourceFile), findVariableStatementContaining("z", sourceFile), createTestClass(), { endPosition: textChanges.TrailingTriviaOption.Exclude, suffix: newLineCharacter }); + changeTracker.replaceNodeRange(sourceFile, findVariableStatementContaining("y", sourceFile), findVariableStatementContaining("z", sourceFile), createTestClass(), { trailingTriviaOption: textChanges.TrailingTriviaOption.Exclude, suffix: newLineCharacter }); }); runSingleFileTest("replaceNodeRange4", /*placeOpenBraceOnNewLineForFunctions*/ true, text, /*validateNodes*/ true, (sourceFile, changeTracker) => { - changeTracker.replaceNodeRange(sourceFile, findVariableStatementContaining("y", sourceFile), findVariableStatementContaining("z", sourceFile), createTestClass(), { startPosition: textChanges.LeadingTriviaOption.Exclude, endPosition: textChanges.TrailingTriviaOption.Exclude }); + changeTracker.replaceNodeRange(sourceFile, findVariableStatementContaining("y", sourceFile), findVariableStatementContaining("z", sourceFile), createTestClass(), { leadingTriviaOption: textChanges.LeadingTriviaOption.Exclude, trailingTriviaOption: textChanges.TrailingTriviaOption.Exclude }); }); } { From bf5123de6acd8159a584ec2103792f988731f8ae Mon Sep 17 00:00:00 2001 From: Gabriela Araujo Britto Date: Tue, 26 Feb 2019 09:49:10 -0800 Subject: [PATCH 109/149] don't export useNonAjustedPositions --- src/services/textChanges.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/services/textChanges.ts b/src/services/textChanges.ts index 529fcef51de..3b08edd6733 100644 --- a/src/services/textChanges.ts +++ b/src/services/textChanges.ts @@ -82,11 +82,12 @@ namespace ts.textChanges { * Usually leading trivia of the variable declaration 'y' should not include trailing trivia (whitespace, comment 'this is x' and newline) from the preceding * variable declaration and trailing trivia for 'y' should include (whitespace, comment 'this is y', newline). * By default when removing nodes we adjust start and end positions to respect specification of the trivia above. - * If pos\end should be interpreted literally 'useNonAdjustedStartPosition' or 'useNonAdjustedEndPosition' should be set to true + * If pos\end should be interpreted literally (that is, withouth including leading and trailing trivia), `leadingTriviaOption` should be set to `LeadingTriviaOption.Exclude` + * and `trailingTriviaOption` to `TrailingTriviaOption.Exclude`. */ export interface ConfigurableStartEnd extends ConfigurableStart, ConfigurableEnd {} - export const useNonAdjustedPositions: ConfigurableStartEnd = { + const useNonAdjustedPositions: ConfigurableStartEnd = { leadingTriviaOption: LeadingTriviaOption.Exclude, trailingTriviaOption: TrailingTriviaOption.Exclude, }; From 970ec62364c532e606f9b6e9d824a6d7e00edb93 Mon Sep 17 00:00:00 2001 From: Gabriela Araujo Britto Date: Tue, 26 Feb 2019 10:02:57 -0800 Subject: [PATCH 110/149] remove unused LeadingTriviaOption and TrailingTriviaOption options --- src/services/textChanges.ts | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/services/textChanges.ts b/src/services/textChanges.ts index 3b08edd6733..81441627635 100644 --- a/src/services/textChanges.ts +++ b/src/services/textChanges.ts @@ -37,8 +37,6 @@ namespace ts.textChanges { export enum LeadingTriviaOption { /** Exclude all leading trivia (use getStart()) */ Exclude, - /** Include leading trivia (default behavior) */ - Include, /** Include leading trivia and, * if there are no line breaks between the node and the previous token, * include all trivia between the node and the previous token @@ -49,8 +47,6 @@ namespace ts.textChanges { export enum TrailingTriviaOption { /** Exclude all trailing trivia (use getEnd()) */ Exclude, - /** TODO (default behavior) */ - IncludeIfLineBreak, /** Include trailing trivia */ Include, } @@ -83,7 +79,7 @@ namespace ts.textChanges { * variable declaration and trailing trivia for 'y' should include (whitespace, comment 'this is y', newline). * By default when removing nodes we adjust start and end positions to respect specification of the trivia above. * If pos\end should be interpreted literally (that is, withouth including leading and trailing trivia), `leadingTriviaOption` should be set to `LeadingTriviaOption.Exclude` - * and `trailingTriviaOption` to `TrailingTriviaOption.Exclude`. + * and `trailingTriviaOption` to `TrailingTriviaOption.Exclude`. */ export interface ConfigurableStartEnd extends ConfigurableStart, ConfigurableEnd {} @@ -1107,7 +1103,7 @@ namespace ts.textChanges { case SyntaxKind.ImportDeclaration: deleteNode(changes, sourceFile, node, // For first import, leave header comment in place - node === sourceFile.imports[0].parent ? { leadingTriviaOption: LeadingTriviaOption.Exclude, trailingTriviaOption: TrailingTriviaOption.IncludeIfLineBreak } : undefined); + node === sourceFile.imports[0].parent ? { leadingTriviaOption: LeadingTriviaOption.Exclude } : undefined); break; case SyntaxKind.BindingElement: From 6fd7011870083105c05aa91591cac88d6766427b Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Mon, 25 Feb 2019 13:07:15 -0800 Subject: [PATCH 111/149] Add test that batches all the open files to update program only once --- src/testRunner/tsconfig.json | 1 + .../tsserver/applyChangesToOpenFiles.ts | 108 ++++++++++++++++++ 2 files changed, 109 insertions(+) create mode 100644 src/testRunner/unittests/tsserver/applyChangesToOpenFiles.ts diff --git a/src/testRunner/tsconfig.json b/src/testRunner/tsconfig.json index 137e4d8af58..4e5c088025c 100644 --- a/src/testRunner/tsconfig.json +++ b/src/testRunner/tsconfig.json @@ -96,6 +96,7 @@ "unittests/tscWatch/resolutionCache.ts", "unittests/tscWatch/watchEnvironment.ts", "unittests/tscWatch/watchApi.ts", + "unittests/tsserver/applyChangesToOpenFiles.ts", "unittests/tsserver/cachingFileSystemInformation.ts", "unittests/tsserver/cancellationToken.ts", "unittests/tsserver/compileOnSave.ts", diff --git a/src/testRunner/unittests/tsserver/applyChangesToOpenFiles.ts b/src/testRunner/unittests/tsserver/applyChangesToOpenFiles.ts new file mode 100644 index 00000000000..f964e77e0eb --- /dev/null +++ b/src/testRunner/unittests/tsserver/applyChangesToOpenFiles.ts @@ -0,0 +1,108 @@ +namespace ts.projectSystem { + describe("unittests:: tsserver:: applyChangesToOpenFiles", () => { + const configFile: File = { + path: "/a/b/tsconfig.json", + content: "{}" + }; + const file3: File = { + path: "/a/b/file3.ts", + content: "let xyz = 1;" + }; + const app: File = { + path: "/a/b/app.ts", + content: "let z = 1;" + }; + + function fileContentWithComment(file: File) { + return `// some copy right notice +${file.content}`; + } + + function verifyText(service: server.ProjectService, file: string, expected: string) { + const info = service.getScriptInfo(file)!; + const snap = info.getSnapshot(); + // Verified applied in reverse order + assert.equal(snap.getText(0, snap.getLength()), expected, `Text of changed file: ${file}`); + } + + function verifyProjectVersion(project: server.Project, expected: number) { + assert.equal(Number(project.getProjectVersion()), expected); + } + + function verify(applyChangesToOpen: (session: TestSession) => void) { + const host = createServerHost([app, file3, commonFile1, commonFile2, libFile, configFile]); + const session = projectSystem.createSession(host); + session.executeCommandSeq({ + command: protocol.CommandTypes.Open, + arguments: { file: app.path } + }); + const service = session.getProjectService(); + const project = service.configuredProjects.get(configFile.path)!; + assert.isDefined(project); + verifyProjectVersion(project, 1); + session.executeCommandSeq({ + command: protocol.CommandTypes.Open, + arguments: { + file: file3.path, + fileContent: fileContentWithComment(file3) + } + }); + verifyProjectVersion(project, 2); + + // Verify Texts + verifyText(service, commonFile1.path, commonFile1.content); + verifyText(service, commonFile2.path, commonFile2.content); + verifyText(service, app.path, app.content); + verifyText(service, file3.path, fileContentWithComment(file3)); + + // Apply changes + applyChangesToOpen(session); + + // Verify again + verifyProjectVersion(project, 5); + // Open file contents + verifyText(service, commonFile1.path, fileContentWithComment(commonFile1)); + verifyText(service, commonFile2.path, fileContentWithComment(commonFile2)); + verifyText(service, app.path, "let zzz = 10;let zz = 10;let z = 1;"); + verifyText(service, file3.path, file3.content); + } + + it("with applyChangedToOpenFiles request", () => { + verify(session => + session.executeCommandSeq({ + command: protocol.CommandTypes.ApplyChangedToOpenFiles, + arguments: { + openFiles: [ + { + fileName: commonFile1.path, + content: fileContentWithComment(commonFile1) + }, + { + fileName: commonFile2.path, + content: fileContentWithComment(commonFile2) + } + ], + changedFiles: [ + { + fileName: app.path, + changes: [ + { + span: { start: 0, length: 0 }, + newText: "let zzz = 10;" + }, + { + span: { start: 0, length: 0 }, + newText: "let zz = 10;" + } + ] + } + ], + closedFiles: [ + file3.path + ] + } + }) + ); + }); + }); +} From 2258bb2fb7f6a4956ccef86fe4a06be10a254cce Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Mon, 25 Feb 2019 14:58:59 -0800 Subject: [PATCH 112/149] Add request applyChangesToOpenFiles --- src/compiler/core.ts | 15 +++++++ src/server/editorServices.ts | 35 ++++++++++++---- src/server/protocol.ts | 27 ++++++++++++ src/server/session.ts | 36 ++++++++++++++-- .../tsserver/applyChangesToOpenFiles.ts | 42 ++++++++++++++++++- .../unittests/tsserver/documentRegistry.ts | 4 +- .../unittests/tsserver/externalProjects.ts | 6 +-- src/testRunner/unittests/tsserver/projects.ts | 19 +++++---- .../reference/api/tsserverlibrary.d.ts | 25 +++++++++++ 9 files changed, 182 insertions(+), 27 deletions(-) diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 4bd4801ce8f..112eca82926 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -1173,6 +1173,21 @@ namespace ts { }}; } + export function arrayReverseIterator(array: ReadonlyArray): Iterator { + let i = array.length; + return { + next: () => { + if (i === 0) { + return { value: undefined as never, done: true }; + } + else { + i--; + return { value: array[i], done: false }; + } + } + }; + } + /** * Stable sort of an array. Elements equal to each other maintain their relative position in the array. */ diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index e9d97f6e03c..ed51028392e 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -407,6 +407,21 @@ namespace ts.server { } } + /*@internal*/ + export interface OpenFileArguments { + fileName: string; + content?: string; + scriptKind?: protocol.ScriptKindName | ScriptKind; + hasMixedContent?: boolean; + projectRootPath?: string; + } + + /*@internal*/ + export interface ChangeFileArguments { + fileName: string; + changes: Iterator; + } + export class ProjectService { /*@internal*/ @@ -2770,18 +2785,22 @@ namespace ts.server { } /* @internal */ - applyChangesInOpenFiles(openFiles: protocol.ExternalFile[] | undefined, changedFiles: protocol.ChangedOpenFile[] | undefined, closedFiles: string[] | undefined): void { + applyChangesInOpenFiles(openFiles: Iterator | undefined, changedFiles?: Iterator, closedFiles?: string[]): void { if (openFiles) { - for (const file of openFiles) { + while (true) { + const { value: file, done } = openFiles.next(); + if (done) break; const scriptInfo = this.getScriptInfo(file.fileName); Debug.assert(!scriptInfo || !scriptInfo.isScriptOpen(), "Script should not exist and not be open already"); const normalizedPath = scriptInfo ? scriptInfo.fileName : toNormalizedPath(file.fileName); - this.openClientFileWithNormalizedPath(normalizedPath, file.content, tryConvertScriptKindName(file.scriptKind!), file.hasMixedContent); // TODO: GH#18217 + this.openClientFileWithNormalizedPath(normalizedPath, file.content, tryConvertScriptKindName(file.scriptKind!), file.hasMixedContent, file.projectRootPath ? toNormalizedPath(file.projectRootPath) : undefined); // TODO: GH#18217 } } if (changedFiles) { - for (const file of changedFiles) { + while (true) { + const { value: file, done } = changedFiles.next(); + if (done) break; const scriptInfo = this.getScriptInfo(file.fileName)!; Debug.assert(!!scriptInfo); this.applyChangesToFile(scriptInfo, file.changes); @@ -2796,10 +2815,10 @@ namespace ts.server { } /* @internal */ - applyChangesToFile(scriptInfo: ScriptInfo, changes: TextChange[]) { - // apply changes in reverse order - for (let i = changes.length - 1; i >= 0; i--) { - const change = changes[i]; + applyChangesToFile(scriptInfo: ScriptInfo, changes: Iterator) { + while (true) { + const { value: change, done } = changes.next(); + if (done) break; scriptInfo.editContent(change.span.start, change.span.start + change.span.length, change.newText); } } diff --git a/src/server/protocol.ts b/src/server/protocol.ts index 1fd8d98b570..3534a991c48 100644 --- a/src/server/protocol.ts +++ b/src/server/protocol.ts @@ -92,6 +92,7 @@ namespace ts.server.protocol { SynchronizeProjectList = "synchronizeProjectList", /* @internal */ ApplyChangedToOpenFiles = "applyChangedToOpenFiles", + ApplyChangesToOpenFiles = "applyChangesToOpenFiles", /* @internal */ EncodedSemanticClassificationsFull = "encodedSemanticClassifications-full", /* @internal */ @@ -1543,6 +1544,32 @@ namespace ts.server.protocol { closedFiles?: string[]; } + /** + * Request to synchronize list of open files with the client + */ + export interface ApplyChangesToOpenFilesRequest extends Request { + command: CommandTypes.ApplyChangesToOpenFiles; + arguments: ApplyChangesToOpenFilesRequestArgs; + } + + /** + * Arguments to ApplyChangesToOpenFilesRequest + */ + export interface ApplyChangesToOpenFilesRequestArgs { + /** + * List of newly open files + */ + openFiles?: OpenRequestArgs[]; + /** + * List of open files files that were changes + */ + changedFiles?: FileCodeEdits[]; + /** + * List of files that were closed + */ + closedFiles?: string[]; + } + /** * Request to set compiler options for inferred projects. * External projects are opened / closed explicitly. diff --git a/src/server/session.ts b/src/server/session.ts index b47dfe6b716..42946002bc4 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -1654,10 +1654,10 @@ namespace ts.server { const end = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); if (start >= 0) { this.changeSeq++; - this.projectService.applyChangesToFile(scriptInfo, [{ + this.projectService.applyChangesToFile(scriptInfo, singleIterator({ span: { start, length: end - start }, newText: args.insertString! // TODO: GH#18217 - }]); + })); } } @@ -2096,9 +2096,39 @@ namespace ts.server { }); return this.requiredResponse(converted); }, + [CommandNames.ApplyChangesToOpenFiles]: (request: protocol.ApplyChangesToOpenFilesRequest) => { + this.changeSeq++; + this.projectService.applyChangesInOpenFiles( + request.arguments.openFiles && mapIterator(arrayIterator(request.arguments.openFiles), file => ({ + fileName: file.file, + content: file.fileContent, + scriptKind: file.scriptKindName, + projectRootPath: file.projectRootPath + })), + request.arguments.changedFiles && mapIterator(arrayIterator(request.arguments.changedFiles), file => ({ + fileName: file.fileName, + changes: mapDefinedIterator(arrayIterator(file.textChanges), change => { + const scriptInfo = Debug.assertDefined(this.projectService.getScriptInfo(file.fileName)); + const start = scriptInfo.lineOffsetToPosition(change.start.line, change.start.offset); + const end = scriptInfo.lineOffsetToPosition(change.end.line, change.end.offset); + return start >= 0 ? { span: { start, length: end - start }, newText: change.newText } : undefined; + }) + })), + request.arguments.closedFiles + ); + return this.requiredResponse(/*response*/ true); + }, [CommandNames.ApplyChangedToOpenFiles]: (request: protocol.ApplyChangedToOpenFilesRequest) => { this.changeSeq++; - this.projectService.applyChangesInOpenFiles(request.arguments.openFiles, request.arguments.changedFiles!, request.arguments.closedFiles!); // TODO: GH#18217 + this.projectService.applyChangesInOpenFiles( + request.arguments.openFiles && arrayIterator(request.arguments.openFiles), + request.arguments.changedFiles && mapIterator(arrayIterator(request.arguments.changedFiles), file => ({ + fileName: file.fileName, + // apply changes in reverse order + changes: arrayReverseIterator(file.changes) + })), + request.arguments.closedFiles + ); // TODO: report errors return this.requiredResponse(/*response*/ true); }, diff --git a/src/testRunner/unittests/tsserver/applyChangesToOpenFiles.ts b/src/testRunner/unittests/tsserver/applyChangesToOpenFiles.ts index f964e77e0eb..e5dd2e58754 100644 --- a/src/testRunner/unittests/tsserver/applyChangesToOpenFiles.ts +++ b/src/testRunner/unittests/tsserver/applyChangesToOpenFiles.ts @@ -31,7 +31,7 @@ ${file.content}`; function verify(applyChangesToOpen: (session: TestSession) => void) { const host = createServerHost([app, file3, commonFile1, commonFile2, libFile, configFile]); - const session = projectSystem.createSession(host); + const session = createSession(host); session.executeCommandSeq({ command: protocol.CommandTypes.Open, arguments: { file: app.path } @@ -104,5 +104,45 @@ ${file.content}`; }) ); }); + + it("with applyChangesToOpenFiles request", () => { + verify(session => + session.executeCommandSeq({ + command: protocol.CommandTypes.ApplyChangesToOpenFiles, + arguments: { + openFiles: [ + { + file: commonFile1.path, + fileContent: fileContentWithComment(commonFile1) + }, + { + file: commonFile2.path, + fileContent: fileContentWithComment(commonFile2) + } + ], + changedFiles: [ + { + fileName: app.path, + textChanges: [ + { + start: { line: 1, offset: 1 }, + end: { line: 1, offset: 1 }, + newText: "let zz = 10;", + }, + { + start: { line: 1, offset: 1 }, + end: { line: 1, offset: 1 }, + newText: "let zzz = 10;", + } + ] + } + ], + closedFiles: [ + file3.path + ] + } + }) + ); + }); }); } diff --git a/src/testRunner/unittests/tsserver/documentRegistry.ts b/src/testRunner/unittests/tsserver/documentRegistry.ts index 1761e413833..10723300cc0 100644 --- a/src/testRunner/unittests/tsserver/documentRegistry.ts +++ b/src/testRunner/unittests/tsserver/documentRegistry.ts @@ -41,13 +41,13 @@ namespace ts.projectSystem { function changeFileToNotImportModule(service: TestProjectService) { const info = service.getScriptInfo(file.path)!; - service.applyChangesToFile(info, [{ span: { start: 0, length: importModuleContent.length }, newText: "" }]); + service.applyChangesToFile(info, singleIterator({ span: { start: 0, length: importModuleContent.length }, newText: "" })); checkProject(service, /*moduleIsOrphan*/ true); } function changeFileToImportModule(service: TestProjectService) { const info = service.getScriptInfo(file.path)!; - service.applyChangesToFile(info, [{ span: { start: 0, length: 0 }, newText: importModuleContent }]); + service.applyChangesToFile(info, singleIterator({ span: { start: 0, length: 0 }, newText: importModuleContent })); checkProject(service, /*moduleIsOrphan*/ false); } diff --git a/src/testRunner/unittests/tsserver/externalProjects.ts b/src/testRunner/unittests/tsserver/externalProjects.ts index 2055141538a..82c706500d3 100644 --- a/src/testRunner/unittests/tsserver/externalProjects.ts +++ b/src/testRunner/unittests/tsserver/externalProjects.ts @@ -161,7 +161,7 @@ namespace ts.projectSystem { checkNumberOfInferredProjects(projectService, 0); externalFiles[0].content = "let x =1;"; - projectService.applyChangesInOpenFiles(externalFiles, [], []); + projectService.applyChangesInOpenFiles(arrayIterator(externalFiles)); }); it("external project that included config files", () => { @@ -790,9 +790,7 @@ namespace ts.projectSystem { rootFiles: [{ fileName: tsconfig.path }, { fileName: jsFilePath }], options: { allowJs: false } }]); - service.applyChangesInOpenFiles([ - { fileName: jsFilePath, scriptKind: ScriptKind.JS, content: "" } - ], /*changedFiles*/ undefined, /*closedFiles*/ undefined); + service.applyChangesInOpenFiles(singleIterator({ fileName: jsFilePath, scriptKind: ScriptKind.JS, content: "" })); checkNumberOfProjects(service, { configuredProjects: 1, inferredProjects: 1 }); checkProjectActualFiles(configProject, [tsconfig.path]); const inferredProject = service.inferredProjects[0]; diff --git a/src/testRunner/unittests/tsserver/projects.ts b/src/testRunner/unittests/tsserver/projects.ts index 3a648c9189e..72eff18f5ba 100644 --- a/src/testRunner/unittests/tsserver/projects.ts +++ b/src/testRunner/unittests/tsserver/projects.ts @@ -202,7 +202,7 @@ namespace ts.projectSystem { const host = createServerHost([file1, config1]); const projectService = createProjectService(host, { useSingleInferredProject: true }, { syntaxOnly: true }); - projectService.applyChangesInOpenFiles([{ fileName: file1.path, content: file1.content }], [], []); + projectService.applyChangesInOpenFiles(singleIterator({ fileName: file1.path, content: file1.content })); checkNumberOfProjects(projectService, { inferredProjects: 1 }); const proj = projectService.inferredProjects[0]; @@ -588,11 +588,11 @@ namespace ts.projectSystem { const host = createServerHost([]); const projectService = createProjectService(host); - projectService.applyChangesInOpenFiles([tsFile], [], []); + projectService.applyChangesInOpenFiles(singleIterator(tsFile)); const projs = projectService.synchronizeProjectList([]); projectService.findProject(projs[0].info!.projectName)!.getLanguageService().getNavigationBarItems(tsFile.fileName); projectService.synchronizeProjectList([projs[0].info!]); - projectService.applyChangesInOpenFiles([jsFile], [], []); + projectService.applyChangesInOpenFiles(singleIterator(jsFile)); }); it("config file is deleted", () => { @@ -696,11 +696,12 @@ namespace ts.projectSystem { checkProjectActualFiles(configuredProjectAt(projectService, 0), [file1.path, file2.path, config.path]); // Open HTML file - projectService.applyChangesInOpenFiles( - /*openFiles*/[{ fileName: file2.path, hasMixedContent: true, scriptKind: ScriptKind.JS, content: `var hello = "hello";` }], - /*changedFiles*/ undefined, - /*closedFiles*/ undefined); - + projectService.applyChangesInOpenFiles(singleIterator({ + fileName: file2.path, + hasMixedContent: true, + scriptKind: ScriptKind.JS, + content: `var hello = "hello";` + })); // Now HTML file is included in the project checkNumberOfProjects(projectService, { configuredProjects: 1 }); checkProjectActualFiles(configuredProjectAt(projectService, 0), [file1.path, file2.path, config.path]); @@ -852,7 +853,7 @@ namespace ts.projectSystem { checkNumberOfProjects(projectService, { inferredProjects: 1 }); projectService.applyChangesInOpenFiles( /*openFiles*/ undefined, - /*changedFiles*/[{ fileName: file1.path, changes: [{ span: createTextSpan(0, file1.path.length), newText: "let y = 1" }] }], + /*changedFiles*/singleIterator({ fileName: file1.path, changes: singleIterator({ span: createTextSpan(0, file1.path.length), newText: "let y = 1" }) }), /*closedFiles*/ undefined); checkNumberOfProjects(projectService, { inferredProjects: 1 }); diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index fab6f905efc..eb522125ddd 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -5720,6 +5720,7 @@ declare namespace ts.server.protocol { OpenExternalProject = "openExternalProject", OpenExternalProjects = "openExternalProjects", CloseExternalProject = "closeExternalProject", + ApplyChangesToOpenFiles = "applyChangesToOpenFiles", GetOutliningSpans = "getOutliningSpans", TodoComments = "todoComments", Indentation = "indentation", @@ -6788,6 +6789,30 @@ declare namespace ts.server.protocol { */ interface CloseExternalProjectResponse extends Response { } + /** + * Request to synchronize list of open files with the client + */ + interface ApplyChangesToOpenFilesRequest extends Request { + command: CommandTypes.ApplyChangesToOpenFiles; + arguments: ApplyChangesToOpenFilesRequestArgs; + } + /** + * Arguments to ApplyChangesToOpenFilesRequest + */ + interface ApplyChangesToOpenFilesRequestArgs { + /** + * List of newly open files + */ + openFiles?: OpenRequestArgs[]; + /** + * List of open files files that were changes + */ + changedFiles?: FileCodeEdits[]; + /** + * List of files that were closed + */ + closedFiles?: string[]; + } /** * Request to set compiler options for inferred projects. * External projects are opened / closed explicitly. From e6068f405bdb371f5edfdeb61e910b4abcd1ee81 Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Tue, 26 Feb 2019 11:43:10 -0800 Subject: [PATCH 113/149] Make applyChangesToOpenFiles efficient to handle batch file opens, close and changes before updating projects Fixes #29667 --- src/server/editorServices.ts | 101 +++++++++++++----- .../tsserver/applyChangesToOpenFiles.ts | 2 +- .../reference/api/tsserverlibrary.d.ts | 4 + 3 files changed, 80 insertions(+), 27 deletions(-) diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index ed51028392e..10939b68114 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -1143,11 +1143,22 @@ namespace ts.server { return project; } + private assignOrphanScriptInfosToInferredProject() { + // collect orphaned files and assign them to inferred project just like we treat open of a file + this.openFiles.forEach((projectRootPath, path) => { + const info = this.getScriptInfoForPath(path as Path)!; + // collect all orphaned script infos from open files + if (info.isOrphan()) { + this.assignOrphanScriptInfoToInferredProject(info, projectRootPath); + } + }); + } + /** * Remove this file from the set of open, non-configured files. * @param info The file that has been closed or newly configured */ - private closeOpenFile(info: ScriptInfo): void { + private closeOpenFile(info: ScriptInfo, skipAssignOrphanScriptInfosToInferredProject?: true) { // Closing file should trigger re-reading the file content from disk. This is // because the user may chose to discard the buffer content before saving // to the disk, and the server's version of the file can be out of sync. @@ -1191,15 +1202,8 @@ namespace ts.server { this.openFiles.delete(info.path); - if (ensureProjectsForOpenFiles) { - // collect orphaned files and assign them to inferred project just like we treat open of a file - this.openFiles.forEach((projectRootPath, path) => { - const info = this.getScriptInfoForPath(path as Path)!; - // collect all orphaned script infos from open files - if (info.isOrphan()) { - this.assignOrphanScriptInfoToInferredProject(info, projectRootPath); - } - }); + if (!skipAssignOrphanScriptInfosToInferredProject && ensureProjectsForOpenFiles) { + this.assignOrphanScriptInfosToInferredProject(); } // Cleanup script infos that arent part of any project (eg. those could be closed script infos not referenced by any project) @@ -1214,6 +1218,8 @@ namespace ts.server { else { this.handleDeletedFile(info); } + + return ensureProjectsForOpenFiles; } private deleteScriptInfo(info: ScriptInfo) { @@ -2585,20 +2591,22 @@ namespace ts.server { }); } - openClientFileWithNormalizedPath(fileName: NormalizedPath, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean, projectRootPath?: NormalizedPath): OpenConfiguredProjectResult { + private getOrCreateOpenScriptInfo(fileName: NormalizedPath, fileContent: string | undefined, scriptKind: ScriptKind | undefined, hasMixedContent: boolean | undefined, projectRootPath: NormalizedPath | undefined) { + const info = this.getOrCreateScriptInfoOpenedByClientForNormalizedPath(fileName, projectRootPath ? this.getNormalizedAbsolutePath(projectRootPath) : this.currentDirectory, fileContent, scriptKind, hasMixedContent)!; // TODO: GH#18217 + this.openFiles.set(info.path, projectRootPath); + return info; + } + + private assignProjectToOpenedScriptInfo(info: ScriptInfo): OpenConfiguredProjectResult { let configFileName: NormalizedPath | undefined; let configFileErrors: ReadonlyArray | undefined; - - const info = this.getOrCreateScriptInfoOpenedByClientForNormalizedPath(fileName, projectRootPath ? this.getNormalizedAbsolutePath(projectRootPath) : this.currentDirectory, fileContent, scriptKind, hasMixedContent)!; // TODO: GH#18217 - - this.openFiles.set(info.path, projectRootPath); let project: ConfiguredProject | ExternalProject | undefined = this.findExternalProjectContainingOpenScriptInfo(info); if (!project && !this.syntaxOnly) { // Checking syntaxOnly is an optimization configFileName = this.getConfigFileNameForFile(info); if (configFileName) { project = this.findConfiguredProjectByProjectName(configFileName); if (!project) { - project = this.createLoadAndUpdateConfiguredProject(configFileName, `Creating possible configured project for ${fileName} to open`); + project = this.createLoadAndUpdateConfiguredProject(configFileName, `Creating possible configured project for ${info.fileName} to open`); // Send the event only if the project got created as part of this open request and info is part of the project if (info.isOrphan()) { // Since the file isnt part of configured project, do not send config file info @@ -2606,7 +2614,7 @@ namespace ts.server { } else { configFileErrors = project.getAllProjectErrors(); - this.sendConfigFileDiagEvent(project, fileName); + this.sendConfigFileDiagEvent(project, info.fileName); } } else { @@ -2628,10 +2636,14 @@ namespace ts.server { // At this point if file is part of any any configured or external project, then it would be present in the containing projects // So if it still doesnt have any containing projects, it needs to be part of inferred project if (info.isOrphan()) { - this.assignOrphanScriptInfoToInferredProject(info, projectRootPath); + Debug.assert(this.openFiles.has(info.path)); + this.assignOrphanScriptInfoToInferredProject(info, this.openFiles.get(info.path)); } Debug.assert(!info.isOrphan()); + return { configFileName, configFileErrors }; + } + private cleanupAfterOpeningFile() { // This was postponed from closeOpenFile to after opening next file, // so that we can reuse the project if we need to right away this.removeOrphanConfiguredProjects(); @@ -2651,9 +2663,14 @@ namespace ts.server { this.removeOrphanScriptInfos(); this.printProjects(); + } + openClientFileWithNormalizedPath(fileName: NormalizedPath, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean, projectRootPath?: NormalizedPath): OpenConfiguredProjectResult { + const info = this.getOrCreateOpenScriptInfo(fileName, fileContent, scriptKind, hasMixedContent, projectRootPath); + const result = this.assignProjectToOpenedScriptInfo(info); + this.cleanupAfterOpeningFile(); this.telemetryOnOpenFile(info); - return { configFileName, configFileErrors }; + return result; } private removeOrphanConfiguredProjects() { @@ -2760,12 +2777,16 @@ namespace ts.server { * Close file whose contents is managed by the client * @param filename is absolute pathname */ - closeClientFile(uncheckedFileName: string) { + closeClientFile(uncheckedFileName: string): void; + /*@internal*/ + closeClientFile(uncheckedFileName: string, skipAssignOrphanScriptInfosToInferredProject: true): boolean; + closeClientFile(uncheckedFileName: string, skipAssignOrphanScriptInfosToInferredProject?: true) { const info = this.getScriptInfoForNormalizedPath(toNormalizedPath(uncheckedFileName)); - if (info) { - this.closeOpenFile(info); + const result = info ? this.closeOpenFile(info, skipAssignOrphanScriptInfosToInferredProject) : false; + if (!skipAssignOrphanScriptInfosToInferredProject) { + this.printProjects(); } - this.printProjects(); + return result; } private collectChanges(lastKnownProjectVersions: protocol.ProjectVersionInfo[], currentProjects: Project[], result: ProjectFilesWithTSDiagnostics[]): void { @@ -2786,14 +2807,23 @@ namespace ts.server { /* @internal */ applyChangesInOpenFiles(openFiles: Iterator | undefined, changedFiles?: Iterator, closedFiles?: string[]): void { + let openScriptInfos: ScriptInfo[] | undefined; + let assignOrphanScriptInfosToInferredProject = false; if (openFiles) { while (true) { const { value: file, done } = openFiles.next(); if (done) break; const scriptInfo = this.getScriptInfo(file.fileName); Debug.assert(!scriptInfo || !scriptInfo.isScriptOpen(), "Script should not exist and not be open already"); - const normalizedPath = scriptInfo ? scriptInfo.fileName : toNormalizedPath(file.fileName); - this.openClientFileWithNormalizedPath(normalizedPath, file.content, tryConvertScriptKindName(file.scriptKind!), file.hasMixedContent, file.projectRootPath ? toNormalizedPath(file.projectRootPath) : undefined); // TODO: GH#18217 + // Create script infos so we have the new content for all the open files before we do any updates to projects + const info = this.getOrCreateOpenScriptInfo( + scriptInfo ? scriptInfo.fileName : toNormalizedPath(file.fileName), + file.content, + tryConvertScriptKindName(file.scriptKind!), + file.hasMixedContent, + file.projectRootPath ? toNormalizedPath(file.projectRootPath) : undefined + ); + (openScriptInfos || (openScriptInfos = [])).push(info); } } @@ -2803,15 +2833,34 @@ namespace ts.server { if (done) break; const scriptInfo = this.getScriptInfo(file.fileName)!; Debug.assert(!!scriptInfo); + // Make edits to script infos and marks containing project as dirty this.applyChangesToFile(scriptInfo, file.changes); } } if (closedFiles) { for (const file of closedFiles) { - this.closeClientFile(file); + // Close files, but dont assign projects to orphan open script infos, that part comes later + assignOrphanScriptInfosToInferredProject = this.closeClientFile(file, /*skipAssignOrphanScriptInfosToInferredProject*/ true) || assignOrphanScriptInfosToInferredProject; } } + + // All the script infos now exist, so ok to go update projects for open files + if (openScriptInfos) { + openScriptInfos.forEach(info => this.assignProjectToOpenedScriptInfo(info)); + } + + // While closing files there could be open files that needed assigning new inferred projects, do it now + if (assignOrphanScriptInfosToInferredProject) { + this.assignOrphanScriptInfosToInferredProject(); + } + + // Cleanup projects + this.cleanupAfterOpeningFile(); + + // Telemetry + forEach(openScriptInfos, info => this.telemetryOnOpenFile(info)); + this.printProjects(); } /* @internal */ diff --git a/src/testRunner/unittests/tsserver/applyChangesToOpenFiles.ts b/src/testRunner/unittests/tsserver/applyChangesToOpenFiles.ts index e5dd2e58754..3c0da365bb5 100644 --- a/src/testRunner/unittests/tsserver/applyChangesToOpenFiles.ts +++ b/src/testRunner/unittests/tsserver/applyChangesToOpenFiles.ts @@ -59,7 +59,7 @@ ${file.content}`; applyChangesToOpen(session); // Verify again - verifyProjectVersion(project, 5); + verifyProjectVersion(project, 3); // Open file contents verifyText(service, commonFile1.path, fileContentWithComment(commonFile1)); verifyText(service, commonFile2.path, fileContentWithComment(commonFile2)); diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index eb522125ddd..f3fdd5158b4 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -8652,6 +8652,7 @@ declare namespace ts.server { */ private onConfigFileChangeForOpenScriptInfo; private removeProject; + private assignOrphanScriptInfosToInferredProject; /** * Remove this file from the set of open, non-configured files. * @param info The file that has been closed or newly configured @@ -8770,6 +8771,9 @@ declare namespace ts.server { */ openClientFile(fileName: string, fileContent?: string, scriptKind?: ScriptKind, projectRootPath?: string): OpenConfiguredProjectResult; private findExternalProjectContainingOpenScriptInfo; + private getOrCreateOpenScriptInfo; + private assignProjectToOpenedScriptInfo; + private cleanupAfterOpeningFile; openClientFileWithNormalizedPath(fileName: NormalizedPath, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean, projectRootPath?: NormalizedPath): OpenConfiguredProjectResult; private removeOrphanConfiguredProjects; private removeOrphanScriptInfos; From ede6b9a5cbf2f2b3c44c706c0a78adfb2326cffc Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Tue, 26 Feb 2019 12:39:01 -0800 Subject: [PATCH 114/149] Issue errors for all circular type parameter constraints --- src/compiler/checker.ts | 19 +++++++++++++++---- src/compiler/diagnosticMessages.json | 4 ++++ 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 958ceae0395..890f8f4beb8 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -7577,7 +7577,19 @@ namespace ts { constraintDepth++; let result = computeBaseConstraint(getSimplifiedType(t)); constraintDepth--; - if (!popTypeResolution() || nonTerminating) { + if (!popTypeResolution()) { + if (t.flags & TypeFlags.TypeParameter) { + const errorNode = getConstraintDeclaration(t); + if (errorNode) { + const diagnostic = error(errorNode, Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(t)); + if (currentNode && !isNodeDescendantOf(errorNode, currentNode) && !isNodeDescendantOf(currentNode, errorNode)) { + addRelatedInfo(diagnostic, createDiagnosticForNode(currentNode, Diagnostics.Circularity_originates_in_type_at_this_location)); + } + } + } + result = circularConstraintType; + } + if (nonTerminating) { result = circularConstraintType; } t.immediateBaseConstraint = result || noConstraintType; @@ -23475,9 +23487,8 @@ namespace ts { checkSourceElement(node.constraint); checkSourceElement(node.default); const typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node)); - if (!hasNonCircularBaseConstraint(typeParameter)) { - error(getEffectiveConstraintOfTypeParameter(node), Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(typeParameter)); - } + // Resolve base constraint to reveal circularity errors + getBaseConstraintOfType(typeParameter); if (!hasNonCircularTypeParameterDefault(typeParameter)) { error(node.default, Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter)); } diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 09b0f721292..5ae3a44b4b9 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -2589,6 +2589,10 @@ "category": "Error", "code": 2750 }, + "Circularity originates in type at this location.": { + "category": "Error", + "code": 2751 + }, "Import declaration '{0}' is using private name '{1}'.": { "category": "Error", From 5270b49bcc7d4e490c606dccd23fb96a3866e626 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Tue, 26 Feb 2019 12:39:14 -0800 Subject: [PATCH 115/149] Accept new baselines --- tests/baselines/reference/recursiveMappedTypes.errors.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/baselines/reference/recursiveMappedTypes.errors.txt b/tests/baselines/reference/recursiveMappedTypes.errors.txt index f2f59052a90..c003204cd78 100644 --- a/tests/baselines/reference/recursiveMappedTypes.errors.txt +++ b/tests/baselines/reference/recursiveMappedTypes.errors.txt @@ -32,6 +32,7 @@ tests/cases/conformance/types/mapped/recursiveMappedTypes.ts(20,19): error TS258 [K in keyof Recurse1]: Recurse1[K] ~~~~~~~~~~~~~~ !!! error TS2313: Type parameter 'K' has a circular constraint. +!!! related TS2751 tests/cases/conformance/types/mapped/recursiveMappedTypes.ts:8:17: Circularity originates in type at this location. } // Repro from #27881 From 2212f4777a90830aa689574821153d41d06ae70c Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Tue, 26 Feb 2019 12:44:12 -0800 Subject: [PATCH 116/149] Add regression test --- .../types/mapped/recursiveMappedTypes.ts | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/tests/cases/conformance/types/mapped/recursiveMappedTypes.ts b/tests/cases/conformance/types/mapped/recursiveMappedTypes.ts index 69a0c1ca597..d5a5d63515f 100644 --- a/tests/cases/conformance/types/mapped/recursiveMappedTypes.ts +++ b/tests/cases/conformance/types/mapped/recursiveMappedTypes.ts @@ -61,3 +61,21 @@ type Remap2 = T extends object ? { [P in keyof T]: Remap2; } : T; type a = Remap1; // string[] type b = Remap2; // string[] + +// Repro from #29992 + +type NonOptionalKeys = { [P in keyof T]: undefined extends T[P] ? never : P }[keyof T]; +type Child = { [P in NonOptionalKeys]: T[P] } + +export interface ListWidget { + "type": "list", + "minimum_count": number, + "maximum_count": number, + "collapsable"?: boolean, //default to false, means all expanded + "each": Child; +} + +type ListChild = Child + +declare let x: ListChild; +x.type; From ecebc9ffeb02e4cd023c30a33e5cf70636124048 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Tue, 26 Feb 2019 12:44:18 -0800 Subject: [PATCH 117/149] Accept new baselines --- .../reference/recursiveMappedTypes.errors.txt | 24 ++++++++- .../reference/recursiveMappedTypes.js | 33 ++++++++++++ .../reference/recursiveMappedTypes.symbols | 54 +++++++++++++++++++ .../reference/recursiveMappedTypes.types | 36 +++++++++++++ 4 files changed, 146 insertions(+), 1 deletion(-) diff --git a/tests/baselines/reference/recursiveMappedTypes.errors.txt b/tests/baselines/reference/recursiveMappedTypes.errors.txt index c003204cd78..43a0e736d25 100644 --- a/tests/baselines/reference/recursiveMappedTypes.errors.txt +++ b/tests/baselines/reference/recursiveMappedTypes.errors.txt @@ -5,9 +5,10 @@ tests/cases/conformance/types/mapped/recursiveMappedTypes.ts(8,11): error TS2313 tests/cases/conformance/types/mapped/recursiveMappedTypes.ts(11,6): error TS2456: Type alias 'Recurse2' circularly references itself. tests/cases/conformance/types/mapped/recursiveMappedTypes.ts(12,11): error TS2313: Type parameter 'K' has a circular constraint. tests/cases/conformance/types/mapped/recursiveMappedTypes.ts(20,19): error TS2589: Type instantiation is excessively deep and possibly infinite. +tests/cases/conformance/types/mapped/recursiveMappedTypes.ts(66,25): error TS2313: Type parameter 'P' has a circular constraint. -==== tests/cases/conformance/types/mapped/recursiveMappedTypes.ts (7 errors) ==== +==== tests/cases/conformance/types/mapped/recursiveMappedTypes.ts (8 errors) ==== // Recursive mapped types simply appear empty type Recurse = { @@ -84,4 +85,25 @@ tests/cases/conformance/types/mapped/recursiveMappedTypes.ts(20,19): error TS258 type a = Remap1; // string[] type b = Remap2; // string[] + + // Repro from #29992 + + type NonOptionalKeys = { [P in keyof T]: undefined extends T[P] ? never : P }[keyof T]; + type Child = { [P in NonOptionalKeys]: T[P] } + ~~~~~~~~~~~~~~~~~~ +!!! error TS2313: Type parameter 'P' has a circular constraint. +!!! related TS2751 tests/cases/conformance/types/mapped/recursiveMappedTypes.ts:79:1: Circularity originates in type at this location. + + export interface ListWidget { + "type": "list", + "minimum_count": number, + "maximum_count": number, + "collapsable"?: boolean, //default to false, means all expanded + "each": Child; + } + + type ListChild = Child + + declare let x: ListChild; + x.type; \ No newline at end of file diff --git a/tests/baselines/reference/recursiveMappedTypes.js b/tests/baselines/reference/recursiveMappedTypes.js index e9e44a1df41..2cda37a8d45 100644 --- a/tests/baselines/reference/recursiveMappedTypes.js +++ b/tests/baselines/reference/recursiveMappedTypes.js @@ -60,6 +60,24 @@ type Remap2 = T extends object ? { [P in keyof T]: Remap2; } : T; type a = Remap1; // string[] type b = Remap2; // string[] + +// Repro from #29992 + +type NonOptionalKeys = { [P in keyof T]: undefined extends T[P] ? never : P }[keyof T]; +type Child = { [P in NonOptionalKeys]: T[P] } + +export interface ListWidget { + "type": "list", + "minimum_count": number, + "maximum_count": number, + "collapsable"?: boolean, //default to false, means all expanded + "each": Child; +} + +type ListChild = Child + +declare let x: ListChild; +x.type; //// [recursiveMappedTypes.js] @@ -70,9 +88,24 @@ function foo(arg) { return arg; } product.users; // (Transform | Transform)[] +x.type; //// [recursiveMappedTypes.d.ts] export declare type Circular = { [P in keyof T]: Circular; }; +declare type NonOptionalKeys = { + [P in keyof T]: undefined extends T[P] ? never : P; +}[keyof T]; +declare type Child = { + [P in NonOptionalKeys]: T[P]; +}; +export interface ListWidget { + "type": "list"; + "minimum_count": number; + "maximum_count": number; + "collapsable"?: boolean; + "each": Child; +} +export {}; diff --git a/tests/baselines/reference/recursiveMappedTypes.symbols b/tests/baselines/reference/recursiveMappedTypes.symbols index 1638dc03f56..777a6a722fa 100644 --- a/tests/baselines/reference/recursiveMappedTypes.symbols +++ b/tests/baselines/reference/recursiveMappedTypes.symbols @@ -165,3 +165,57 @@ type b = Remap2; // string[] >b : Symbol(b, Decl(recursiveMappedTypes.ts, 59, 26)) >Remap2 : Symbol(Remap2, Decl(recursiveMappedTypes.ts, 56, 51)) +// Repro from #29992 + +type NonOptionalKeys = { [P in keyof T]: undefined extends T[P] ? never : P }[keyof T]; +>NonOptionalKeys : Symbol(NonOptionalKeys, Decl(recursiveMappedTypes.ts, 60, 26)) +>T : Symbol(T, Decl(recursiveMappedTypes.ts, 64, 21)) +>P : Symbol(P, Decl(recursiveMappedTypes.ts, 64, 29)) +>T : Symbol(T, Decl(recursiveMappedTypes.ts, 64, 21)) +>T : Symbol(T, Decl(recursiveMappedTypes.ts, 64, 21)) +>P : Symbol(P, Decl(recursiveMappedTypes.ts, 64, 29)) +>P : Symbol(P, Decl(recursiveMappedTypes.ts, 64, 29)) +>T : Symbol(T, Decl(recursiveMappedTypes.ts, 64, 21)) + +type Child = { [P in NonOptionalKeys]: T[P] } +>Child : Symbol(Child, Decl(recursiveMappedTypes.ts, 64, 90)) +>T : Symbol(T, Decl(recursiveMappedTypes.ts, 65, 11)) +>P : Symbol(P, Decl(recursiveMappedTypes.ts, 65, 19)) +>NonOptionalKeys : Symbol(NonOptionalKeys, Decl(recursiveMappedTypes.ts, 60, 26)) +>T : Symbol(T, Decl(recursiveMappedTypes.ts, 65, 11)) +>T : Symbol(T, Decl(recursiveMappedTypes.ts, 65, 11)) +>P : Symbol(P, Decl(recursiveMappedTypes.ts, 65, 19)) + +export interface ListWidget { +>ListWidget : Symbol(ListWidget, Decl(recursiveMappedTypes.ts, 65, 51)) + + "type": "list", +>"type" : Symbol(ListWidget["type"], Decl(recursiveMappedTypes.ts, 67, 29)) + + "minimum_count": number, +>"minimum_count" : Symbol(ListWidget["minimum_count"], Decl(recursiveMappedTypes.ts, 68, 19)) + + "maximum_count": number, +>"maximum_count" : Symbol(ListWidget["maximum_count"], Decl(recursiveMappedTypes.ts, 69, 28)) + + "collapsable"?: boolean, //default to false, means all expanded +>"collapsable" : Symbol(ListWidget["collapsable"], Decl(recursiveMappedTypes.ts, 70, 28)) + + "each": Child; +>"each" : Symbol(ListWidget["each"], Decl(recursiveMappedTypes.ts, 71, 28)) +>Child : Symbol(Child, Decl(recursiveMappedTypes.ts, 64, 90)) +>ListWidget : Symbol(ListWidget, Decl(recursiveMappedTypes.ts, 65, 51)) +} + +type ListChild = Child +>ListChild : Symbol(ListChild, Decl(recursiveMappedTypes.ts, 73, 1)) +>Child : Symbol(Child, Decl(recursiveMappedTypes.ts, 64, 90)) +>ListWidget : Symbol(ListWidget, Decl(recursiveMappedTypes.ts, 65, 51)) + +declare let x: ListChild; +>x : Symbol(x, Decl(recursiveMappedTypes.ts, 77, 11)) +>ListChild : Symbol(ListChild, Decl(recursiveMappedTypes.ts, 73, 1)) + +x.type; +>x : Symbol(x, Decl(recursiveMappedTypes.ts, 77, 11)) + diff --git a/tests/baselines/reference/recursiveMappedTypes.types b/tests/baselines/reference/recursiveMappedTypes.types index 126d1e1d740..34cfd2d6100 100644 --- a/tests/baselines/reference/recursiveMappedTypes.types +++ b/tests/baselines/reference/recursiveMappedTypes.types @@ -97,3 +97,39 @@ type a = Remap1; // string[] type b = Remap2; // string[] >b : string[] +// Repro from #29992 + +type NonOptionalKeys = { [P in keyof T]: undefined extends T[P] ? never : P }[keyof T]; +>NonOptionalKeys : { [P in keyof T]: undefined extends T[P] ? never : P; }[keyof T] + +type Child = { [P in NonOptionalKeys]: T[P] } +>Child : Child + +export interface ListWidget { + "type": "list", +>"type" : "list" + + "minimum_count": number, +>"minimum_count" : number + + "maximum_count": number, +>"maximum_count" : number + + "collapsable"?: boolean, //default to false, means all expanded +>"collapsable" : boolean + + "each": Child; +>"each" : Child +} + +type ListChild = Child +>ListChild : Child + +declare let x: ListChild; +>x : Child + +x.type; +>x.type : any +>x : Child +>type : any + From 2533d8294ef8f88537339a3daf54e6c7925552c0 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Tue, 26 Feb 2019 13:43:22 -0800 Subject: [PATCH 118/149] Make a fresh empty object literal not a subtype of a type with an index signaure (#29975) * Forbid inferable index checkign during subtype relationship checking * Merge object.values and object.entries overloads to work around subtype change * Invert subtype relationship between fresh empty objects and non-empty object types * Remvoe comment * Revert lib change * Remove trailing whitespace ffs --- src/compiler/checker.ts | 5 + ...IndexSignatureContainingObject1.errors.txt | 53 ++++++++ ...ubtypeOfIndexSignatureContainingObject1.js | 58 ++++++++ ...eOfIndexSignatureContainingObject1.symbols | 118 ++++++++++++++++ ...ypeOfIndexSignatureContainingObject1.types | 88 ++++++++++++ ...IndexSignatureContainingObject2.errors.txt | 54 ++++++++ ...ubtypeOfIndexSignatureContainingObject2.js | 60 +++++++++ ...eOfIndexSignatureContainingObject2.symbols | 127 ++++++++++++++++++ ...ypeOfIndexSignatureContainingObject2.types | 99 ++++++++++++++ ...ubtypeOfIndexSignatureContainingObject1.ts | 42 ++++++ ...ubtypeOfIndexSignatureContainingObject2.ts | 43 ++++++ 11 files changed, 747 insertions(+) create mode 100644 tests/baselines/reference/emptyObjectNotSubtypeOfIndexSignatureContainingObject1.errors.txt create mode 100644 tests/baselines/reference/emptyObjectNotSubtypeOfIndexSignatureContainingObject1.js create mode 100644 tests/baselines/reference/emptyObjectNotSubtypeOfIndexSignatureContainingObject1.symbols create mode 100644 tests/baselines/reference/emptyObjectNotSubtypeOfIndexSignatureContainingObject1.types create mode 100644 tests/baselines/reference/emptyObjectNotSubtypeOfIndexSignatureContainingObject2.errors.txt create mode 100644 tests/baselines/reference/emptyObjectNotSubtypeOfIndexSignatureContainingObject2.js create mode 100644 tests/baselines/reference/emptyObjectNotSubtypeOfIndexSignatureContainingObject2.symbols create mode 100644 tests/baselines/reference/emptyObjectNotSubtypeOfIndexSignatureContainingObject2.types create mode 100644 tests/cases/compiler/emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts create mode 100644 tests/cases/compiler/emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index ddc958df0b4..4777092a7fd 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -12787,6 +12787,11 @@ namespace ts { else if (isReadonlyArrayType(target) ? isArrayType(source) || isTupleType(source) : isArrayType(target) && isTupleType(source) && !source.target.readonly) { return isRelatedTo(getIndexTypeOfType(source, IndexKind.Number) || anyType, getIndexTypeOfType(target, IndexKind.Number) || anyType, reportErrors); } + // Consider a fresh empty object literal type "closed" under the subtype relationship - this way `{} <- {[idx: string]: any} <- fresh({})` + // and not `{} <- fresh({}) <- {[idx: string]: any}` + else if (relation === subtypeRelation && isEmptyObjectType(target) && getObjectFlags(target) & ObjectFlags.FreshLiteral && !isEmptyObjectType(source)) { + return Ternary.False; + } // Even if relationship doesn't hold for unions, intersections, or generic type references, // it may hold in a structural comparison. // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates diff --git a/tests/baselines/reference/emptyObjectNotSubtypeOfIndexSignatureContainingObject1.errors.txt b/tests/baselines/reference/emptyObjectNotSubtypeOfIndexSignatureContainingObject1.errors.txt new file mode 100644 index 00000000000..56135cf8b0d --- /dev/null +++ b/tests/baselines/reference/emptyObjectNotSubtypeOfIndexSignatureContainingObject1.errors.txt @@ -0,0 +1,53 @@ +tests/cases/compiler/emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts(41,3): error TS2322: Type 'Dictionary' is not assignable to type 'Record'. + Index signatures are incompatible. + Type 'string' is not assignable to type 'Bar'. + + +==== tests/cases/compiler/emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts (1 errors) ==== + // This should behave the same as emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts + // Begin types from Lodash. + interface Dictionary { + [index: string]: T; + } + + interface NumericDictionary { + [index: number]: T; + } + + type ObjectIterator = ( + value: TObject[keyof TObject], + key: string, + collection: TObject + ) => TResult; + + type DictionaryIterator = ObjectIterator, TResult>; + + // In lodash.d.ts this function has many overloads, but this seems to be the problematic one. + function mapValues( + obj: Dictionary | NumericDictionary | null | undefined, + callback: DictionaryIterator + ): Dictionary { + return null as any; + } + // End types from Lodash. + + interface Foo { + foo: string; + } + + interface Bar { + bar: string; + } + + export function fooToBar( + foos: Record + ): Record { + const result = foos == null ? {} : mapValues(foos, f => f.foo); + // This line _should_ fail, because `result` is not the right type. + return result; + ~~~~~~~~~~~~~~ +!!! error TS2322: Type 'Dictionary' is not assignable to type 'Record'. +!!! error TS2322: Index signatures are incompatible. +!!! error TS2322: Type 'string' is not assignable to type 'Bar'. + } + \ No newline at end of file diff --git a/tests/baselines/reference/emptyObjectNotSubtypeOfIndexSignatureContainingObject1.js b/tests/baselines/reference/emptyObjectNotSubtypeOfIndexSignatureContainingObject1.js new file mode 100644 index 00000000000..38418b365a2 --- /dev/null +++ b/tests/baselines/reference/emptyObjectNotSubtypeOfIndexSignatureContainingObject1.js @@ -0,0 +1,58 @@ +//// [emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts] +// This should behave the same as emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts +// Begin types from Lodash. +interface Dictionary { + [index: string]: T; +} + +interface NumericDictionary { + [index: number]: T; +} + +type ObjectIterator = ( + value: TObject[keyof TObject], + key: string, + collection: TObject +) => TResult; + +type DictionaryIterator = ObjectIterator, TResult>; + +// In lodash.d.ts this function has many overloads, but this seems to be the problematic one. +function mapValues( + obj: Dictionary | NumericDictionary | null | undefined, + callback: DictionaryIterator +): Dictionary { + return null as any; +} +// End types from Lodash. + +interface Foo { + foo: string; +} + +interface Bar { + bar: string; +} + +export function fooToBar( + foos: Record +): Record { + const result = foos == null ? {} : mapValues(foos, f => f.foo); + // This line _should_ fail, because `result` is not the right type. + return result; +} + + +//// [emptyObjectNotSubtypeOfIndexSignatureContainingObject1.js] +"use strict"; +exports.__esModule = true; +// In lodash.d.ts this function has many overloads, but this seems to be the problematic one. +function mapValues(obj, callback) { + return null; +} +function fooToBar(foos) { + var result = foos == null ? {} : mapValues(foos, function (f) { return f.foo; }); + // This line _should_ fail, because `result` is not the right type. + return result; +} +exports.fooToBar = fooToBar; diff --git a/tests/baselines/reference/emptyObjectNotSubtypeOfIndexSignatureContainingObject1.symbols b/tests/baselines/reference/emptyObjectNotSubtypeOfIndexSignatureContainingObject1.symbols new file mode 100644 index 00000000000..2d808fb5138 --- /dev/null +++ b/tests/baselines/reference/emptyObjectNotSubtypeOfIndexSignatureContainingObject1.symbols @@ -0,0 +1,118 @@ +=== tests/cases/compiler/emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts === +// This should behave the same as emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts +// Begin types from Lodash. +interface Dictionary { +>Dictionary : Symbol(Dictionary, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 0, 0)) +>T : Symbol(T, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 2, 21)) + + [index: string]: T; +>index : Symbol(index, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 3, 3)) +>T : Symbol(T, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 2, 21)) +} + +interface NumericDictionary { +>NumericDictionary : Symbol(NumericDictionary, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 4, 1)) +>T : Symbol(T, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 6, 28)) + + [index: number]: T; +>index : Symbol(index, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 7, 3)) +>T : Symbol(T, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 6, 28)) +} + +type ObjectIterator = ( +>ObjectIterator : Symbol(ObjectIterator, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 8, 1)) +>TObject : Symbol(TObject, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 10, 20)) +>TResult : Symbol(TResult, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 10, 28)) + + value: TObject[keyof TObject], +>value : Symbol(value, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 10, 41)) +>TObject : Symbol(TObject, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 10, 20)) +>TObject : Symbol(TObject, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 10, 20)) + + key: string, +>key : Symbol(key, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 11, 32)) + + collection: TObject +>collection : Symbol(collection, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 12, 14)) +>TObject : Symbol(TObject, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 10, 20)) + +) => TResult; +>TResult : Symbol(TResult, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 10, 28)) + +type DictionaryIterator = ObjectIterator, TResult>; +>DictionaryIterator : Symbol(DictionaryIterator, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 14, 13)) +>T : Symbol(T, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 16, 24)) +>TResult : Symbol(TResult, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 16, 26)) +>ObjectIterator : Symbol(ObjectIterator, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 8, 1)) +>Dictionary : Symbol(Dictionary, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 0, 0)) +>T : Symbol(T, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 16, 24)) +>TResult : Symbol(TResult, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 16, 26)) + +// In lodash.d.ts this function has many overloads, but this seems to be the problematic one. +function mapValues( +>mapValues : Symbol(mapValues, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 16, 77)) +>T : Symbol(T, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 19, 19)) +>TResult : Symbol(TResult, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 19, 21)) + + obj: Dictionary | NumericDictionary | null | undefined, +>obj : Symbol(obj, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 19, 31)) +>Dictionary : Symbol(Dictionary, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 0, 0)) +>T : Symbol(T, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 19, 19)) +>NumericDictionary : Symbol(NumericDictionary, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 4, 1)) +>T : Symbol(T, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 19, 19)) + + callback: DictionaryIterator +>callback : Symbol(callback, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 20, 63)) +>DictionaryIterator : Symbol(DictionaryIterator, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 14, 13)) +>T : Symbol(T, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 19, 19)) +>TResult : Symbol(TResult, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 19, 21)) + +): Dictionary { +>Dictionary : Symbol(Dictionary, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 0, 0)) +>TResult : Symbol(TResult, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 19, 21)) + + return null as any; +} +// End types from Lodash. + +interface Foo { +>Foo : Symbol(Foo, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 24, 1)) + + foo: string; +>foo : Symbol(Foo.foo, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 27, 15)) +} + +interface Bar { +>Bar : Symbol(Bar, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 29, 1)) + + bar: string; +>bar : Symbol(Bar.bar, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 31, 15)) +} + +export function fooToBar( +>fooToBar : Symbol(fooToBar, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 33, 1)) + + foos: Record +>foos : Symbol(foos, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 35, 25)) +>Record : Symbol(Record, Decl(lib.es5.d.ts, --, --)) +>Foo : Symbol(Foo, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 24, 1)) + +): Record { +>Record : Symbol(Record, Decl(lib.es5.d.ts, --, --)) +>Bar : Symbol(Bar, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 29, 1)) + + const result = foos == null ? {} : mapValues(foos, f => f.foo); +>result : Symbol(result, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 38, 7)) +>foos : Symbol(foos, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 35, 25)) +>mapValues : Symbol(mapValues, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 16, 77)) +>foos : Symbol(foos, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 35, 25)) +>f : Symbol(f, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 38, 52)) +>f.foo : Symbol(Foo.foo, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 27, 15)) +>f : Symbol(f, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 38, 52)) +>foo : Symbol(Foo.foo, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 27, 15)) + + // This line _should_ fail, because `result` is not the right type. + return result; +>result : Symbol(result, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts, 38, 7)) +} + diff --git a/tests/baselines/reference/emptyObjectNotSubtypeOfIndexSignatureContainingObject1.types b/tests/baselines/reference/emptyObjectNotSubtypeOfIndexSignatureContainingObject1.types new file mode 100644 index 00000000000..6426ab89c8a --- /dev/null +++ b/tests/baselines/reference/emptyObjectNotSubtypeOfIndexSignatureContainingObject1.types @@ -0,0 +1,88 @@ +=== tests/cases/compiler/emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts === +// This should behave the same as emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts +// Begin types from Lodash. +interface Dictionary { + [index: string]: T; +>index : string +} + +interface NumericDictionary { + [index: number]: T; +>index : number +} + +type ObjectIterator = ( +>ObjectIterator : ObjectIterator + + value: TObject[keyof TObject], +>value : TObject[keyof TObject] + + key: string, +>key : string + + collection: TObject +>collection : TObject + +) => TResult; + +type DictionaryIterator = ObjectIterator, TResult>; +>DictionaryIterator : ObjectIterator, TResult> + +// In lodash.d.ts this function has many overloads, but this seems to be the problematic one. +function mapValues( +>mapValues : (obj: Dictionary | NumericDictionary, callback: ObjectIterator, TResult>) => Dictionary + + obj: Dictionary | NumericDictionary | null | undefined, +>obj : Dictionary | NumericDictionary +>null : null + + callback: DictionaryIterator +>callback : ObjectIterator, TResult> + +): Dictionary { + return null as any; +>null as any : any +>null : null +} +// End types from Lodash. + +interface Foo { + foo: string; +>foo : string +} + +interface Bar { + bar: string; +>bar : string +} + +export function fooToBar( +>fooToBar : (foos: Record) => Record + + foos: Record +>foos : Record + +): Record { +>null : null + + const result = foos == null ? {} : mapValues(foos, f => f.foo); +>result : Dictionary +>foos == null ? {} : mapValues(foos, f => f.foo) : Dictionary +>foos == null : boolean +>foos : Record +>null : null +>{} : {} +>mapValues(foos, f => f.foo) : Dictionary +>mapValues : (obj: Dictionary | NumericDictionary, callback: ObjectIterator, TResult>) => Dictionary +>foos : Record +>f => f.foo : (f: Foo) => string +>f : Foo +>f.foo : string +>f : Foo +>foo : string + + // This line _should_ fail, because `result` is not the right type. + return result; +>result : Dictionary +} + diff --git a/tests/baselines/reference/emptyObjectNotSubtypeOfIndexSignatureContainingObject2.errors.txt b/tests/baselines/reference/emptyObjectNotSubtypeOfIndexSignatureContainingObject2.errors.txt new file mode 100644 index 00000000000..58de4631483 --- /dev/null +++ b/tests/baselines/reference/emptyObjectNotSubtypeOfIndexSignatureContainingObject2.errors.txt @@ -0,0 +1,54 @@ +tests/cases/compiler/emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts(42,3): error TS2322: Type 'Dictionary' is not assignable to type 'Record'. + Index signatures are incompatible. + Type 'string' is not assignable to type 'Bar'. + + +==== tests/cases/compiler/emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts (1 errors) ==== + // This should behave the same as emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts + // Begin types from Lodash. + interface Dictionary { + [index: string]: T; + } + + interface NumericDictionary { + [index: number]: T; + } + + type ObjectIterator = ( + value: TObject[keyof TObject], + key: string, + collection: TObject + ) => TResult; + + type DictionaryIterator = ObjectIterator, TResult>; + + // In lodash.d.ts this function has many overloads, but this seems to be the problematic one. + function mapValues( + obj: Dictionary | NumericDictionary | null | undefined, + callback: DictionaryIterator + ): Dictionary { + return null as any; + } + // End types from Lodash. + + interface Foo { + foo: string; + } + + interface Bar { + bar: string; + } + + export function fooToBar( + foos: Record + ): Record { + const wat = mapValues(foos, f => f.foo); + const result = foos == null ? {} : mapValues(foos, f => f.foo); + // This line _should_ fail, because `result` is not the right type. + return result; + ~~~~~~~~~~~~~~ +!!! error TS2322: Type 'Dictionary' is not assignable to type 'Record'. +!!! error TS2322: Index signatures are incompatible. +!!! error TS2322: Type 'string' is not assignable to type 'Bar'. + } + \ No newline at end of file diff --git a/tests/baselines/reference/emptyObjectNotSubtypeOfIndexSignatureContainingObject2.js b/tests/baselines/reference/emptyObjectNotSubtypeOfIndexSignatureContainingObject2.js new file mode 100644 index 00000000000..b2193cc3101 --- /dev/null +++ b/tests/baselines/reference/emptyObjectNotSubtypeOfIndexSignatureContainingObject2.js @@ -0,0 +1,60 @@ +//// [emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts] +// This should behave the same as emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts +// Begin types from Lodash. +interface Dictionary { + [index: string]: T; +} + +interface NumericDictionary { + [index: number]: T; +} + +type ObjectIterator = ( + value: TObject[keyof TObject], + key: string, + collection: TObject +) => TResult; + +type DictionaryIterator = ObjectIterator, TResult>; + +// In lodash.d.ts this function has many overloads, but this seems to be the problematic one. +function mapValues( + obj: Dictionary | NumericDictionary | null | undefined, + callback: DictionaryIterator +): Dictionary { + return null as any; +} +// End types from Lodash. + +interface Foo { + foo: string; +} + +interface Bar { + bar: string; +} + +export function fooToBar( + foos: Record +): Record { + const wat = mapValues(foos, f => f.foo); + const result = foos == null ? {} : mapValues(foos, f => f.foo); + // This line _should_ fail, because `result` is not the right type. + return result; +} + + +//// [emptyObjectNotSubtypeOfIndexSignatureContainingObject2.js] +"use strict"; +exports.__esModule = true; +// In lodash.d.ts this function has many overloads, but this seems to be the problematic one. +function mapValues(obj, callback) { + return null; +} +function fooToBar(foos) { + var wat = mapValues(foos, function (f) { return f.foo; }); + var result = foos == null ? {} : mapValues(foos, function (f) { return f.foo; }); + // This line _should_ fail, because `result` is not the right type. + return result; +} +exports.fooToBar = fooToBar; diff --git a/tests/baselines/reference/emptyObjectNotSubtypeOfIndexSignatureContainingObject2.symbols b/tests/baselines/reference/emptyObjectNotSubtypeOfIndexSignatureContainingObject2.symbols new file mode 100644 index 00000000000..8ce432231e1 --- /dev/null +++ b/tests/baselines/reference/emptyObjectNotSubtypeOfIndexSignatureContainingObject2.symbols @@ -0,0 +1,127 @@ +=== tests/cases/compiler/emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts === +// This should behave the same as emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts +// Begin types from Lodash. +interface Dictionary { +>Dictionary : Symbol(Dictionary, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 0, 0)) +>T : Symbol(T, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 2, 21)) + + [index: string]: T; +>index : Symbol(index, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 3, 3)) +>T : Symbol(T, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 2, 21)) +} + +interface NumericDictionary { +>NumericDictionary : Symbol(NumericDictionary, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 4, 1)) +>T : Symbol(T, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 6, 28)) + + [index: number]: T; +>index : Symbol(index, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 7, 3)) +>T : Symbol(T, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 6, 28)) +} + +type ObjectIterator = ( +>ObjectIterator : Symbol(ObjectIterator, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 8, 1)) +>TObject : Symbol(TObject, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 10, 20)) +>TResult : Symbol(TResult, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 10, 28)) + + value: TObject[keyof TObject], +>value : Symbol(value, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 10, 41)) +>TObject : Symbol(TObject, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 10, 20)) +>TObject : Symbol(TObject, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 10, 20)) + + key: string, +>key : Symbol(key, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 11, 32)) + + collection: TObject +>collection : Symbol(collection, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 12, 14)) +>TObject : Symbol(TObject, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 10, 20)) + +) => TResult; +>TResult : Symbol(TResult, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 10, 28)) + +type DictionaryIterator = ObjectIterator, TResult>; +>DictionaryIterator : Symbol(DictionaryIterator, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 14, 13)) +>T : Symbol(T, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 16, 24)) +>TResult : Symbol(TResult, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 16, 26)) +>ObjectIterator : Symbol(ObjectIterator, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 8, 1)) +>Dictionary : Symbol(Dictionary, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 0, 0)) +>T : Symbol(T, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 16, 24)) +>TResult : Symbol(TResult, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 16, 26)) + +// In lodash.d.ts this function has many overloads, but this seems to be the problematic one. +function mapValues( +>mapValues : Symbol(mapValues, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 16, 77)) +>T : Symbol(T, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 19, 19)) +>TResult : Symbol(TResult, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 19, 21)) + + obj: Dictionary | NumericDictionary | null | undefined, +>obj : Symbol(obj, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 19, 31)) +>Dictionary : Symbol(Dictionary, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 0, 0)) +>T : Symbol(T, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 19, 19)) +>NumericDictionary : Symbol(NumericDictionary, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 4, 1)) +>T : Symbol(T, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 19, 19)) + + callback: DictionaryIterator +>callback : Symbol(callback, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 20, 63)) +>DictionaryIterator : Symbol(DictionaryIterator, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 14, 13)) +>T : Symbol(T, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 19, 19)) +>TResult : Symbol(TResult, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 19, 21)) + +): Dictionary { +>Dictionary : Symbol(Dictionary, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 0, 0)) +>TResult : Symbol(TResult, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 19, 21)) + + return null as any; +} +// End types from Lodash. + +interface Foo { +>Foo : Symbol(Foo, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 24, 1)) + + foo: string; +>foo : Symbol(Foo.foo, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 27, 15)) +} + +interface Bar { +>Bar : Symbol(Bar, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 29, 1)) + + bar: string; +>bar : Symbol(Bar.bar, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 31, 15)) +} + +export function fooToBar( +>fooToBar : Symbol(fooToBar, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 33, 1)) + + foos: Record +>foos : Symbol(foos, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 35, 25)) +>Record : Symbol(Record, Decl(lib.es5.d.ts, --, --)) +>Foo : Symbol(Foo, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 24, 1)) + +): Record { +>Record : Symbol(Record, Decl(lib.es5.d.ts, --, --)) +>Bar : Symbol(Bar, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 29, 1)) + + const wat = mapValues(foos, f => f.foo); +>wat : Symbol(wat, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 38, 7)) +>mapValues : Symbol(mapValues, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 16, 77)) +>foos : Symbol(foos, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 35, 25)) +>f : Symbol(f, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 38, 29)) +>f.foo : Symbol(Foo.foo, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 27, 15)) +>f : Symbol(f, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 38, 29)) +>foo : Symbol(Foo.foo, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 27, 15)) + + const result = foos == null ? {} : mapValues(foos, f => f.foo); +>result : Symbol(result, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 39, 7)) +>foos : Symbol(foos, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 35, 25)) +>mapValues : Symbol(mapValues, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 16, 77)) +>foos : Symbol(foos, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 35, 25)) +>f : Symbol(f, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 39, 52)) +>f.foo : Symbol(Foo.foo, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 27, 15)) +>f : Symbol(f, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 39, 52)) +>foo : Symbol(Foo.foo, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 27, 15)) + + // This line _should_ fail, because `result` is not the right type. + return result; +>result : Symbol(result, Decl(emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts, 39, 7)) +} + diff --git a/tests/baselines/reference/emptyObjectNotSubtypeOfIndexSignatureContainingObject2.types b/tests/baselines/reference/emptyObjectNotSubtypeOfIndexSignatureContainingObject2.types new file mode 100644 index 00000000000..fd536cbd849 --- /dev/null +++ b/tests/baselines/reference/emptyObjectNotSubtypeOfIndexSignatureContainingObject2.types @@ -0,0 +1,99 @@ +=== tests/cases/compiler/emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts === +// This should behave the same as emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts +// Begin types from Lodash. +interface Dictionary { + [index: string]: T; +>index : string +} + +interface NumericDictionary { + [index: number]: T; +>index : number +} + +type ObjectIterator = ( +>ObjectIterator : ObjectIterator + + value: TObject[keyof TObject], +>value : TObject[keyof TObject] + + key: string, +>key : string + + collection: TObject +>collection : TObject + +) => TResult; + +type DictionaryIterator = ObjectIterator, TResult>; +>DictionaryIterator : ObjectIterator, TResult> + +// In lodash.d.ts this function has many overloads, but this seems to be the problematic one. +function mapValues( +>mapValues : (obj: Dictionary | NumericDictionary, callback: ObjectIterator, TResult>) => Dictionary + + obj: Dictionary | NumericDictionary | null | undefined, +>obj : Dictionary | NumericDictionary +>null : null + + callback: DictionaryIterator +>callback : ObjectIterator, TResult> + +): Dictionary { + return null as any; +>null as any : any +>null : null +} +// End types from Lodash. + +interface Foo { + foo: string; +>foo : string +} + +interface Bar { + bar: string; +>bar : string +} + +export function fooToBar( +>fooToBar : (foos: Record) => Record + + foos: Record +>foos : Record + +): Record { +>null : null + + const wat = mapValues(foos, f => f.foo); +>wat : Dictionary +>mapValues(foos, f => f.foo) : Dictionary +>mapValues : (obj: Dictionary | NumericDictionary, callback: ObjectIterator, TResult>) => Dictionary +>foos : Record +>f => f.foo : (f: Foo) => string +>f : Foo +>f.foo : string +>f : Foo +>foo : string + + const result = foos == null ? {} : mapValues(foos, f => f.foo); +>result : Dictionary +>foos == null ? {} : mapValues(foos, f => f.foo) : Dictionary +>foos == null : boolean +>foos : Record +>null : null +>{} : {} +>mapValues(foos, f => f.foo) : Dictionary +>mapValues : (obj: Dictionary | NumericDictionary, callback: ObjectIterator, TResult>) => Dictionary +>foos : Record +>f => f.foo : (f: Foo) => string +>f : Foo +>f.foo : string +>f : Foo +>foo : string + + // This line _should_ fail, because `result` is not the right type. + return result; +>result : Dictionary +} + diff --git a/tests/cases/compiler/emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts b/tests/cases/compiler/emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts new file mode 100644 index 00000000000..3638ae796a7 --- /dev/null +++ b/tests/cases/compiler/emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts @@ -0,0 +1,42 @@ +// This should behave the same as emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts +// Begin types from Lodash. +interface Dictionary { + [index: string]: T; +} + +interface NumericDictionary { + [index: number]: T; +} + +type ObjectIterator = ( + value: TObject[keyof TObject], + key: string, + collection: TObject +) => TResult; + +type DictionaryIterator = ObjectIterator, TResult>; + +// In lodash.d.ts this function has many overloads, but this seems to be the problematic one. +function mapValues( + obj: Dictionary | NumericDictionary | null | undefined, + callback: DictionaryIterator +): Dictionary { + return null as any; +} +// End types from Lodash. + +interface Foo { + foo: string; +} + +interface Bar { + bar: string; +} + +export function fooToBar( + foos: Record +): Record { + const result = foos == null ? {} : mapValues(foos, f => f.foo); + // This line _should_ fail, because `result` is not the right type. + return result; +} diff --git a/tests/cases/compiler/emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts b/tests/cases/compiler/emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts new file mode 100644 index 00000000000..3c59e141b30 --- /dev/null +++ b/tests/cases/compiler/emptyObjectNotSubtypeOfIndexSignatureContainingObject2.ts @@ -0,0 +1,43 @@ +// This should behave the same as emptyObjectNotSubtypeOfIndexSignatureContainingObject1.ts +// Begin types from Lodash. +interface Dictionary { + [index: string]: T; +} + +interface NumericDictionary { + [index: number]: T; +} + +type ObjectIterator = ( + value: TObject[keyof TObject], + key: string, + collection: TObject +) => TResult; + +type DictionaryIterator = ObjectIterator, TResult>; + +// In lodash.d.ts this function has many overloads, but this seems to be the problematic one. +function mapValues( + obj: Dictionary | NumericDictionary | null | undefined, + callback: DictionaryIterator +): Dictionary { + return null as any; +} +// End types from Lodash. + +interface Foo { + foo: string; +} + +interface Bar { + bar: string; +} + +export function fooToBar( + foos: Record +): Record { + const wat = mapValues(foos, f => f.foo); + const result = foos == null ? {} : mapValues(foos, f => f.foo); + // This line _should_ fail, because `result` is not the right type. + return result; +} From 288851066bdfaba4822b7ce2b92829b22d05c79a Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Tue, 26 Feb 2019 13:43:41 -0800 Subject: [PATCH 119/149] Dont create a union type to infer conditional type branches (#30010) --- src/compiler/checker.ts | 3 +- ...onalTypeRelaxingConstraintAssignability.js | 39 ++++++++++ ...ypeRelaxingConstraintAssignability.symbols | 73 +++++++++++++++++++ ...lTypeRelaxingConstraintAssignability.types | 64 ++++++++++++++++ ...onalTypeRelaxingConstraintAssignability.ts | 24 ++++++ 5 files changed, 202 insertions(+), 1 deletion(-) create mode 100644 tests/baselines/reference/conditionalTypeRelaxingConstraintAssignability.js create mode 100644 tests/baselines/reference/conditionalTypeRelaxingConstraintAssignability.symbols create mode 100644 tests/baselines/reference/conditionalTypeRelaxingConstraintAssignability.types create mode 100644 tests/cases/compiler/conditionalTypeRelaxingConstraintAssignability.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 4777092a7fd..002fdecc0cd 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -14519,7 +14519,8 @@ namespace ts { inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); } else if (target.flags & TypeFlags.Conditional) { - inferFromTypes(source, getUnionType([getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)])); + inferFromTypes(source, getTrueTypeFromConditionalType(target)); + inferFromTypes(source, getFalseTypeFromConditionalType(target)); } else if (target.flags & TypeFlags.UnionOrIntersection) { for (const t of (target).types) { diff --git a/tests/baselines/reference/conditionalTypeRelaxingConstraintAssignability.js b/tests/baselines/reference/conditionalTypeRelaxingConstraintAssignability.js new file mode 100644 index 00000000000..f066b18d5c6 --- /dev/null +++ b/tests/baselines/reference/conditionalTypeRelaxingConstraintAssignability.js @@ -0,0 +1,39 @@ +//// [conditionalTypeRelaxingConstraintAssignability.ts] +export type ElChildren = + | ElChildren.Void + | ElChildren.Text; +export namespace ElChildren { + export type Void = undefined; + export type Text = string; +} + +type Relax = C extends ElChildren.Text ? ElChildren.Text : C; + +export class Elem< + C extends ElChildren, + > { + constructor( + private children_: Relax, + ) { + } +} + +new Elem(undefined as ElChildren.Void); +new Elem('' as ElChildren.Text); +new Elem('' as ElChildren.Void | ElChildren.Text); // error +new Elem('' as ElChildren); // error + +//// [conditionalTypeRelaxingConstraintAssignability.js] +"use strict"; +exports.__esModule = true; +var Elem = /** @class */ (function () { + function Elem(children_) { + this.children_ = children_; + } + return Elem; +}()); +exports.Elem = Elem; +new Elem(undefined); +new Elem(''); +new Elem(''); // error +new Elem(''); // error diff --git a/tests/baselines/reference/conditionalTypeRelaxingConstraintAssignability.symbols b/tests/baselines/reference/conditionalTypeRelaxingConstraintAssignability.symbols new file mode 100644 index 00000000000..7ce85b0fbfa --- /dev/null +++ b/tests/baselines/reference/conditionalTypeRelaxingConstraintAssignability.symbols @@ -0,0 +1,73 @@ +=== tests/cases/compiler/conditionalTypeRelaxingConstraintAssignability.ts === +export type ElChildren = +>ElChildren : Symbol(ElChildren, Decl(conditionalTypeRelaxingConstraintAssignability.ts, 0, 0), Decl(conditionalTypeRelaxingConstraintAssignability.ts, 2, 20)) + + | ElChildren.Void +>ElChildren : Symbol(ElChildren, Decl(conditionalTypeRelaxingConstraintAssignability.ts, 0, 0), Decl(conditionalTypeRelaxingConstraintAssignability.ts, 2, 20)) +>Void : Symbol(ElChildren.Void, Decl(conditionalTypeRelaxingConstraintAssignability.ts, 3, 29)) + + | ElChildren.Text; +>ElChildren : Symbol(ElChildren, Decl(conditionalTypeRelaxingConstraintAssignability.ts, 0, 0), Decl(conditionalTypeRelaxingConstraintAssignability.ts, 2, 20)) +>Text : Symbol(ElChildren.Text, Decl(conditionalTypeRelaxingConstraintAssignability.ts, 4, 31)) + +export namespace ElChildren { +>ElChildren : Symbol(ElChildren, Decl(conditionalTypeRelaxingConstraintAssignability.ts, 0, 0), Decl(conditionalTypeRelaxingConstraintAssignability.ts, 2, 20)) + + export type Void = undefined; +>Void : Symbol(Void, Decl(conditionalTypeRelaxingConstraintAssignability.ts, 3, 29)) + + export type Text = string; +>Text : Symbol(Text, Decl(conditionalTypeRelaxingConstraintAssignability.ts, 4, 31)) +} + +type Relax = C extends ElChildren.Text ? ElChildren.Text : C; +>Relax : Symbol(Relax, Decl(conditionalTypeRelaxingConstraintAssignability.ts, 6, 1)) +>C : Symbol(C, Decl(conditionalTypeRelaxingConstraintAssignability.ts, 8, 11)) +>ElChildren : Symbol(ElChildren, Decl(conditionalTypeRelaxingConstraintAssignability.ts, 0, 0), Decl(conditionalTypeRelaxingConstraintAssignability.ts, 2, 20)) +>C : Symbol(C, Decl(conditionalTypeRelaxingConstraintAssignability.ts, 8, 11)) +>ElChildren : Symbol(ElChildren, Decl(conditionalTypeRelaxingConstraintAssignability.ts, 0, 0), Decl(conditionalTypeRelaxingConstraintAssignability.ts, 2, 20)) +>Text : Symbol(ElChildren.Text, Decl(conditionalTypeRelaxingConstraintAssignability.ts, 4, 31)) +>ElChildren : Symbol(ElChildren, Decl(conditionalTypeRelaxingConstraintAssignability.ts, 0, 0), Decl(conditionalTypeRelaxingConstraintAssignability.ts, 2, 20)) +>Text : Symbol(ElChildren.Text, Decl(conditionalTypeRelaxingConstraintAssignability.ts, 4, 31)) +>C : Symbol(C, Decl(conditionalTypeRelaxingConstraintAssignability.ts, 8, 11)) + +export class Elem< +>Elem : Symbol(Elem, Decl(conditionalTypeRelaxingConstraintAssignability.ts, 8, 83)) + + C extends ElChildren, +>C : Symbol(C, Decl(conditionalTypeRelaxingConstraintAssignability.ts, 10, 18)) +>ElChildren : Symbol(ElChildren, Decl(conditionalTypeRelaxingConstraintAssignability.ts, 0, 0), Decl(conditionalTypeRelaxingConstraintAssignability.ts, 2, 20)) + + > { + constructor( + private children_: Relax, +>children_ : Symbol(Elem.children_, Decl(conditionalTypeRelaxingConstraintAssignability.ts, 13, 14)) +>Relax : Symbol(Relax, Decl(conditionalTypeRelaxingConstraintAssignability.ts, 6, 1)) +>C : Symbol(C, Decl(conditionalTypeRelaxingConstraintAssignability.ts, 10, 18)) + + ) { + } +} + +new Elem(undefined as ElChildren.Void); +>Elem : Symbol(Elem, Decl(conditionalTypeRelaxingConstraintAssignability.ts, 8, 83)) +>undefined : Symbol(undefined) +>ElChildren : Symbol(ElChildren, Decl(conditionalTypeRelaxingConstraintAssignability.ts, 0, 0), Decl(conditionalTypeRelaxingConstraintAssignability.ts, 2, 20)) +>Void : Symbol(ElChildren.Void, Decl(conditionalTypeRelaxingConstraintAssignability.ts, 3, 29)) + +new Elem('' as ElChildren.Text); +>Elem : Symbol(Elem, Decl(conditionalTypeRelaxingConstraintAssignability.ts, 8, 83)) +>ElChildren : Symbol(ElChildren, Decl(conditionalTypeRelaxingConstraintAssignability.ts, 0, 0), Decl(conditionalTypeRelaxingConstraintAssignability.ts, 2, 20)) +>Text : Symbol(ElChildren.Text, Decl(conditionalTypeRelaxingConstraintAssignability.ts, 4, 31)) + +new Elem('' as ElChildren.Void | ElChildren.Text); // error +>Elem : Symbol(Elem, Decl(conditionalTypeRelaxingConstraintAssignability.ts, 8, 83)) +>ElChildren : Symbol(ElChildren, Decl(conditionalTypeRelaxingConstraintAssignability.ts, 0, 0), Decl(conditionalTypeRelaxingConstraintAssignability.ts, 2, 20)) +>Void : Symbol(ElChildren.Void, Decl(conditionalTypeRelaxingConstraintAssignability.ts, 3, 29)) +>ElChildren : Symbol(ElChildren, Decl(conditionalTypeRelaxingConstraintAssignability.ts, 0, 0), Decl(conditionalTypeRelaxingConstraintAssignability.ts, 2, 20)) +>Text : Symbol(ElChildren.Text, Decl(conditionalTypeRelaxingConstraintAssignability.ts, 4, 31)) + +new Elem('' as ElChildren); // error +>Elem : Symbol(Elem, Decl(conditionalTypeRelaxingConstraintAssignability.ts, 8, 83)) +>ElChildren : Symbol(ElChildren, Decl(conditionalTypeRelaxingConstraintAssignability.ts, 0, 0), Decl(conditionalTypeRelaxingConstraintAssignability.ts, 2, 20)) + diff --git a/tests/baselines/reference/conditionalTypeRelaxingConstraintAssignability.types b/tests/baselines/reference/conditionalTypeRelaxingConstraintAssignability.types new file mode 100644 index 00000000000..c827e26bddb --- /dev/null +++ b/tests/baselines/reference/conditionalTypeRelaxingConstraintAssignability.types @@ -0,0 +1,64 @@ +=== tests/cases/compiler/conditionalTypeRelaxingConstraintAssignability.ts === +export type ElChildren = +>ElChildren : ElChildren + + | ElChildren.Void +>ElChildren : any + + | ElChildren.Text; +>ElChildren : any + +export namespace ElChildren { + export type Void = undefined; +>Void : undefined + + export type Text = string; +>Text : string +} + +type Relax = C extends ElChildren.Text ? ElChildren.Text : C; +>Relax : Relax +>ElChildren : any +>ElChildren : any + +export class Elem< +>Elem : Elem + + C extends ElChildren, + > { + constructor( + private children_: Relax, +>children_ : Relax + + ) { + } +} + +new Elem(undefined as ElChildren.Void); +>new Elem(undefined as ElChildren.Void) : Elem +>Elem : typeof Elem +>undefined as ElChildren.Void : undefined +>undefined : undefined +>ElChildren : any + +new Elem('' as ElChildren.Text); +>new Elem('' as ElChildren.Text) : Elem +>Elem : typeof Elem +>'' as ElChildren.Text : string +>'' : "" +>ElChildren : any + +new Elem('' as ElChildren.Void | ElChildren.Text); // error +>new Elem('' as ElChildren.Void | ElChildren.Text) : Elem +>Elem : typeof Elem +>'' as ElChildren.Void | ElChildren.Text : ElChildren +>'' : "" +>ElChildren : any +>ElChildren : any + +new Elem('' as ElChildren); // error +>new Elem('' as ElChildren) : Elem +>Elem : typeof Elem +>'' as ElChildren : ElChildren +>'' : "" + diff --git a/tests/cases/compiler/conditionalTypeRelaxingConstraintAssignability.ts b/tests/cases/compiler/conditionalTypeRelaxingConstraintAssignability.ts new file mode 100644 index 00000000000..2f18e464e3b --- /dev/null +++ b/tests/cases/compiler/conditionalTypeRelaxingConstraintAssignability.ts @@ -0,0 +1,24 @@ +// @strict: true +export type ElChildren = + | ElChildren.Void + | ElChildren.Text; +export namespace ElChildren { + export type Void = undefined; + export type Text = string; +} + +type Relax = C extends ElChildren.Text ? ElChildren.Text : C; + +export class Elem< + C extends ElChildren, + > { + constructor( + private children_: Relax, + ) { + } +} + +new Elem(undefined as ElChildren.Void); +new Elem('' as ElChildren.Text); +new Elem('' as ElChildren.Void | ElChildren.Text); // error +new Elem('' as ElChildren); // error \ No newline at end of file From 3e4b9c07d28c5a5347d297fe4da669a0b0fa4d5c Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Tue, 26 Feb 2019 14:01:03 -0800 Subject: [PATCH 120/149] Revert "Do not wrap npm path with quotes" This reverts commit 1ed5e1c63b71e0a4e7fd0493a37e43a7ef518ebb. --- src/typingsInstaller/nodeTypingsInstaller.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/typingsInstaller/nodeTypingsInstaller.ts b/src/typingsInstaller/nodeTypingsInstaller.ts index 2facb1223d0..1d75218c883 100644 --- a/src/typingsInstaller/nodeTypingsInstaller.ts +++ b/src/typingsInstaller/nodeTypingsInstaller.ts @@ -89,6 +89,10 @@ namespace ts.server.typingsInstaller { log); this.npmPath = npmLocation !== undefined ? npmLocation : getDefaultNPMLocation(process.argv[0]); + // If the NPM path contains spaces and isn't wrapped in quotes, do so. + if (stringContains(this.npmPath, " ") && this.npmPath[0] !== `"`) { + this.npmPath = `"${this.npmPath}"`; + } if (this.log.isEnabled()) { this.log.writeLine(`Process id: ${process.pid}`); this.log.writeLine(`NPM location: ${this.npmPath} (explicit '${Arguments.NpmLocation}' ${npmLocation === undefined ? "not " : ""} provided)`); From fd10c12116b7caf5fe8766812c3c26fac4f43c9c Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Tue, 26 Feb 2019 14:01:42 -0800 Subject: [PATCH 121/149] Revert "Use execFileSync in typing installer" This reverts commit bc386c11fd3f026ca84ec556b1b8fb4a2eee0038. --- .../unittests/tsserver/typingsInstaller.ts | 12 ++++++------ src/typingsInstaller/nodeTypingsInstaller.ts | 16 ++++++++-------- src/typingsInstallerCore/typingsInstaller.ts | 17 +++++------------ 3 files changed, 19 insertions(+), 26 deletions(-) diff --git a/src/testRunner/unittests/tsserver/typingsInstaller.ts b/src/testRunner/unittests/tsserver/typingsInstaller.ts index 5d648ba23a2..76df9934682 100644 --- a/src/testRunner/unittests/tsserver/typingsInstaller.ts +++ b/src/testRunner/unittests/tsserver/typingsInstaller.ts @@ -1684,9 +1684,9 @@ namespace ts.projectSystem { TI.getNpmCommandForInstallation(npmPath, tsVersion, packageNames, packageNames.length - Math.ceil(packageNames.length / 2)).command ]; it("works when the command is too long to install all packages at once", () => { - const commands: [string, string[]][] = []; - const hasError = TI.installNpmPackages(npmPath, tsVersion, packageNames, (file, args) => { - commands.push([file, args]); + const commands: string[] = []; + const hasError = TI.installNpmPackages(npmPath, tsVersion, packageNames, command => { + commands.push(command); return false; }); assert.isFalse(hasError); @@ -1694,9 +1694,9 @@ namespace ts.projectSystem { }); it("installs remaining packages when one of the partial command fails", () => { - const commands: [string, string[]][] = []; - const hasError = TI.installNpmPackages(npmPath, tsVersion, packageNames, (file, args) => { - commands.push([file, args]); + const commands: string[] = []; + const hasError = TI.installNpmPackages(npmPath, tsVersion, packageNames, command => { + commands.push(command); return commands.length === 1; }); assert.isTrue(hasError); diff --git a/src/typingsInstaller/nodeTypingsInstaller.ts b/src/typingsInstaller/nodeTypingsInstaller.ts index 1d75218c883..62bdcfce260 100644 --- a/src/typingsInstaller/nodeTypingsInstaller.ts +++ b/src/typingsInstaller/nodeTypingsInstaller.ts @@ -70,10 +70,10 @@ namespace ts.server.typingsInstaller { cwd: string; encoding: "utf-8"; } - type ExecFileSync = (file: string, args: string[], options: ExecSyncOptions) => string; + type ExecSync = (command: string, options: ExecSyncOptions) => string; export class NodeTypingsInstaller extends TypingsInstaller { - private readonly nodeExecFileSync: ExecFileSync; + private readonly nodeExecSync: ExecSync; private readonly npmPath: string; readonly typesRegistry: Map>; @@ -97,7 +97,7 @@ namespace ts.server.typingsInstaller { this.log.writeLine(`Process id: ${process.pid}`); this.log.writeLine(`NPM location: ${this.npmPath} (explicit '${Arguments.NpmLocation}' ${npmLocation === undefined ? "not " : ""} provided)`); } - ({ execFileSync: this.nodeExecFileSync } = require("child_process")); + ({ execSync: this.nodeExecSync } = require("child_process")); this.ensurePackageDirectoryExists(globalTypingsCacheLocation); @@ -105,7 +105,7 @@ namespace ts.server.typingsInstaller { if (this.log.isEnabled()) { this.log.writeLine(`Updating ${typesRegistryPackageName} npm package...`); } - this.execFileSyncAndLog(this.npmPath, ["install", "--ignore-scripts", `${typesRegistryPackageName}@${this.latestDistTag}`], { cwd: globalTypingsCacheLocation }); + this.execSyncAndLog(`${this.npmPath} install --ignore-scripts ${typesRegistryPackageName}@${this.latestDistTag}`, { cwd: globalTypingsCacheLocation }); if (this.log.isEnabled()) { this.log.writeLine(`Updated ${typesRegistryPackageName} npm package`); } @@ -189,7 +189,7 @@ namespace ts.server.typingsInstaller { this.log.writeLine(`#${requestId} with arguments'${JSON.stringify(packageNames)}'.`); } const start = Date.now(); - const hasError = installNpmPackages(this.npmPath, version, packageNames, (file, args) => this.execFileSyncAndLog(file, args, { cwd })); + const hasError = installNpmPackages(this.npmPath, version, packageNames, command => this.execSyncAndLog(command, { cwd })); if (this.log.isEnabled()) { this.log.writeLine(`npm install #${requestId} took: ${Date.now() - start} ms`); } @@ -197,12 +197,12 @@ namespace ts.server.typingsInstaller { } /** Returns 'true' in case of error. */ - private execFileSyncAndLog(file: string, args: string[], options: Pick): boolean { + private execSyncAndLog(command: string, options: Pick): boolean { if (this.log.isEnabled()) { - this.log.writeLine(`Exec: ${file} ${args.join(" ")}`); + this.log.writeLine(`Exec: ${command}`); } try { - const stdout = this.nodeExecFileSync(file, args, { ...options, encoding: "utf-8" }); + const stdout = this.nodeExecSync(command, { ...options, encoding: "utf-8" }); if (this.log.isEnabled()) { this.log.writeLine(` Succeeded. stdout:${indent(sys.newLine, stdout)}`); } diff --git a/src/typingsInstallerCore/typingsInstaller.ts b/src/typingsInstallerCore/typingsInstaller.ts index 3d0858d7dfe..df83f1a677c 100644 --- a/src/typingsInstallerCore/typingsInstaller.ts +++ b/src/typingsInstallerCore/typingsInstaller.ts @@ -31,35 +31,28 @@ namespace ts.server.typingsInstaller { } /*@internal*/ - export function installNpmPackages(npmPath: string, tsVersion: string, packageNames: string[], install: (file: string, args: string[]) => boolean) { + export function installNpmPackages(npmPath: string, tsVersion: string, packageNames: string[], install: (command: string) => boolean) { let hasError = false; for (let remaining = packageNames.length; remaining > 0;) { const result = getNpmCommandForInstallation(npmPath, tsVersion, packageNames, remaining); remaining = result.remaining; - hasError = install(result.command[0], result.command[1]) || hasError; + hasError = install(result.command) || hasError; } return hasError; } - function getUserAgent(tsVersion: string) { - return `--user-agent="typesInstaller/${tsVersion}"`; - } - const npmInstall = "install", ignoreScripts = "--ignore-scripts", saveDev = "--save-dev"; - const commandBaseLength = npmInstall.length + ignoreScripts.length + saveDev.length + getUserAgent("").length + 5; /*@internal*/ export function getNpmCommandForInstallation(npmPath: string, tsVersion: string, packageNames: string[], remaining: number) { const sliceStart = packageNames.length - remaining; - let packages: string[], toSlice = remaining; + let command: string, toSlice = remaining; while (true) { - packages = toSlice === packageNames.length ? packageNames : packageNames.slice(sliceStart, sliceStart + toSlice); - const commandLength = npmPath.length + commandBaseLength + packages.join(" ").length + tsVersion.length; - if (commandLength < 8000) { + command = `${npmPath} install --ignore-scripts ${(toSlice === packageNames.length ? packageNames : packageNames.slice(sliceStart, sliceStart + toSlice)).join(" ")} --save-dev --user-agent="typesInstaller/${tsVersion}"`; + if (command.length < 8000) { break; } toSlice = toSlice - Math.floor(toSlice / 2); } - const command: [string, string[]] = [npmPath, [npmInstall, ignoreScripts, ...packages, saveDev, getUserAgent(tsVersion)]]; return { command, remaining: remaining - toSlice }; } From 006fe14bcc670e2c47afce6cd69c26f2467b6f03 Mon Sep 17 00:00:00 2001 From: Gabriela Araujo Britto Date: Tue, 26 Feb 2019 16:22:08 -0800 Subject: [PATCH 122/149] refactor utilities --- src/services/utilities.ts | 65 ++++++++++----------------------------- 1 file changed, 17 insertions(+), 48 deletions(-) diff --git a/src/services/utilities.ts b/src/services/utilities.ts index 0536e6f34ea..afa14f62a1d 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -1753,33 +1753,23 @@ namespace ts { /** * Sets EmitFlags to suppress leading and trailing trivia on the node. */ - export function suppressLeadingAndTrailingTrivia(node: Node, recursive = true) { - suppressLeadingTrivia(node, recursive); - suppressTrailingTrivia(node, recursive); + export function suppressLeadingAndTrailingTrivia(node: Node) { + suppressLeadingTrivia(node); + suppressTrailingTrivia(node); } /** * Sets EmitFlags to suppress leading trivia on the node. */ - export function suppressLeadingTrivia(node: Node, recursive = true) { - if (recursive) { - addEmitFlagsRecursively(node, EmitFlags.NoLeadingComments, getFirstChild); - } - else { - addEmitFlags(node, EmitFlags.NoLeadingComments); - } + export function suppressLeadingTrivia(node: Node) { + addEmitFlagsRecursively(node, EmitFlags.NoLeadingComments, getFirstChild); } /** * Sets EmitFlags to suppress trailing trivia on the node. */ - export function suppressTrailingTrivia(node: Node, recursive = true) { - if (recursive) { - addEmitFlagsRecursively(node, EmitFlags.NoTrailingComments, getLastChild); - } - else { - addEmitFlags(node, EmitFlags.NoTrailingComments); - } + export function suppressTrailingTrivia(node: Node) { + addEmitFlagsRecursively(node, EmitFlags.NoTrailingComments, getLastChild); } function addEmitFlagsRecursively(node: Node, flag: EmitFlags, getChild: (n: Node) => Node | undefined) { @@ -1832,35 +1822,12 @@ namespace ts { } export function copyLeadingComments(sourceNode: Node, targetNode: Node, sourceFile: SourceFile, commentKind?: CommentKind, hasTrailingNewLine?: boolean) { - forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, (pos, end, kind, htnl) => { - if (kind === SyntaxKind.MultiLineCommentTrivia) { - // Remove leading /* - pos += 2; - // Remove trailing */ - end -= 2; - } - else { - // Remove leading // - pos += 2; - } - addSyntheticLeadingComment(targetNode, commentKind || kind, sourceFile.text.slice(pos, end), hasTrailingNewLine !== undefined ? hasTrailingNewLine : htnl); - }); + forEachLeadingCommentRange(sourceFile.text, sourceNode.pos, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, addSyntheticLeadingComment)); } + export function copyTrailingComments(sourceNode: Node, targetNode: Node, sourceFile: SourceFile, commentKind?: CommentKind, hasTrailingNewLine?: boolean) { - forEachTrailingCommentRange(sourceFile.text, sourceNode.end, (pos, end, kind, htnl) => { - if (kind === SyntaxKind.MultiLineCommentTrivia) { - // Remove leading /* - pos += 2; - // Remove trailing */ - end -= 2; - } - else { - // Remove leading // - pos += 2; - } - addSyntheticTrailingComment(targetNode, commentKind || kind, sourceFile.text.slice(pos, end), hasTrailingNewLine !== undefined ? hasTrailingNewLine : htnl); - }); + forEachTrailingCommentRange(sourceFile.text, sourceNode.end, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, addSyntheticTrailingComment)); } /** @@ -1871,7 +1838,11 @@ namespace ts { * The comment refers to `a` but belongs to the `(` token, but we might want to copy it. */ export function copyTrailingAsLeadingComments(sourceNode: Node, targetNode: Node, sourceFile: SourceFile, commentKind?: CommentKind, hasTrailingNewLine?: boolean) { - forEachTrailingCommentRange(sourceFile.text, sourceNode.pos, (pos, end, kind, htnl) => { + forEachTrailingCommentRange(sourceFile.text, sourceNode.pos, getAddCommentsFunction(targetNode, sourceFile, commentKind, hasTrailingNewLine, addSyntheticLeadingComment)); + } + + function getAddCommentsFunction(targetNode: Node, sourceFile: SourceFile, commentKind: CommentKind | undefined, hasTrailingNewLine: boolean | undefined, cb: (node: Node, kind: CommentKind, text: string, hasTrailingNewLine?: boolean) => void) { + return (pos: number, end: number, kind: CommentKind, htnl: boolean) => { if (kind === SyntaxKind.MultiLineCommentTrivia) { // Remove leading /* pos += 2; @@ -1882,12 +1853,10 @@ namespace ts { // Remove leading // pos += 2; } - addSyntheticLeadingComment(targetNode, commentKind || kind, sourceFile.text.slice(pos, end), hasTrailingNewLine !== undefined ? hasTrailingNewLine : htnl); - }); + cb(targetNode, commentKind || kind, sourceFile.text.slice(pos, end), hasTrailingNewLine !== undefined ? hasTrailingNewLine : htnl); + }; } - - function indexInTextChange(change: string, name: string): number { if (startsWith(change, name)) return 0; // Add a " " to avoid references inside words From aedffe049d74ba1893d92dbec41b0f389609c364 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Wed, 27 Feb 2019 11:50:04 -0800 Subject: [PATCH 123/149] Revert "Merge pull request #27697 from mattmccutchen/issue-27118" This reverts commit 2dfb6202ed03e04ba1dcc330eea219c50fe48c66, reversing changes made to bbf559b9c7fd21b984d7cb538140c74e3d6a6b45. --- src/compiler/checker.ts | 9 +- .../reference/conditionalTypes2.errors.txt | 122 ++- .../baselines/reference/conditionalTypes2.js | 121 ++- .../reference/conditionalTypes2.symbols | 870 +++++++++--------- .../reference/conditionalTypes2.types | 115 ++- .../types/conditional/conditionalTypes2.ts | 57 +- 6 files changed, 687 insertions(+), 607 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 7e6cb97a930..80853ca2eaf 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -12724,11 +12724,10 @@ namespace ts { else if (source.flags & TypeFlags.Conditional) { if (target.flags & TypeFlags.Conditional) { // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if - // they have the same distributivity, T1 and T2 are identical types, U1 and U2 are identical - // types, X1 is related to X2, and Y1 is related to Y2. - if ((source).root.isDistributive === (target).root.isDistributive && - isTypeIdenticalTo((source).extendsType, (target).extendsType) && - isTypeIdenticalTo((source).checkType, (target).checkType)) { + // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2, + // and Y1 is related to Y2. + if (isTypeIdenticalTo((source).extendsType, (target).extendsType) && + (isRelatedTo((source).checkType, (target).checkType) || isRelatedTo((target).checkType, (source).checkType))) { if (result = isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), reportErrors)) { result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors); } diff --git a/tests/baselines/reference/conditionalTypes2.errors.txt b/tests/baselines/reference/conditionalTypes2.errors.txt index 343a0a8412c..a1a23b6da18 100644 --- a/tests/baselines/reference/conditionalTypes2.errors.txt +++ b/tests/baselines/reference/conditionalTypes2.errors.txt @@ -1,38 +1,29 @@ -tests/cases/conformance/types/conditional/conditionalTypes2.ts(16,5): error TS2322: Type 'Covariant' is not assignable to type 'Covariant'. - Types of property 'foo' are incompatible. - Type 'B extends string ? B : number' is not assignable to type 'A extends string ? A : number'. -tests/cases/conformance/types/conditional/conditionalTypes2.ts(17,5): error TS2322: Type 'Covariant' is not assignable to type 'Covariant'. - Types of property 'foo' are incompatible. - Type 'A extends string ? A : number' is not assignable to type 'B extends string ? B : number'. -tests/cases/conformance/types/conditional/conditionalTypes2.ts(21,5): error TS2322: Type 'Contravariant' is not assignable to type 'Contravariant'. - Types of property 'foo' are incompatible. - Type 'B extends string ? keyof B : number' is not assignable to type 'A extends string ? keyof A : number'. -tests/cases/conformance/types/conditional/conditionalTypes2.ts(22,5): error TS2322: Type 'Contravariant' is not assignable to type 'Contravariant'. - Types of property 'foo' are incompatible. - Type 'A extends string ? keyof A : number' is not assignable to type 'B extends string ? keyof B : number'. -tests/cases/conformance/types/conditional/conditionalTypes2.ts(26,5): error TS2322: Type 'Invariant' is not assignable to type 'Invariant'. +tests/cases/conformance/types/conditional/conditionalTypes2.ts(15,5): error TS2322: Type 'Covariant' is not assignable to type 'Covariant'. + Type 'A' is not assignable to type 'B'. +tests/cases/conformance/types/conditional/conditionalTypes2.ts(19,5): error TS2322: Type 'Contravariant' is not assignable to type 'Contravariant'. + Type 'A' is not assignable to type 'B'. +tests/cases/conformance/types/conditional/conditionalTypes2.ts(24,5): error TS2322: Type 'Invariant' is not assignable to type 'Invariant'. Types of property 'foo' are incompatible. Type 'B extends string ? keyof B : B' is not assignable to type 'A extends string ? keyof A : A'. -tests/cases/conformance/types/conditional/conditionalTypes2.ts(27,5): error TS2322: Type 'Invariant' is not assignable to type 'Invariant'. + Type 'keyof B' is not assignable to type 'keyof A'. + Type 'string | number | symbol' is not assignable to type 'keyof A'. + Type 'string' is not assignable to type 'keyof A'. +tests/cases/conformance/types/conditional/conditionalTypes2.ts(25,5): error TS2322: Type 'Invariant' is not assignable to type 'Invariant'. Types of property 'foo' are incompatible. Type 'A extends string ? keyof A : A' is not assignable to type 'B extends string ? keyof B : B'. -tests/cases/conformance/types/conditional/conditionalTypes2.ts(75,12): error TS2345: Argument of type 'Extract, Bar>' is not assignable to parameter of type '{ foo: string; bat: string; }'. + Type 'A' is not assignable to type 'B'. +tests/cases/conformance/types/conditional/conditionalTypes2.ts(73,12): error TS2345: Argument of type 'Extract, Bar>' is not assignable to parameter of type '{ foo: string; bat: string; }'. Property 'bat' is missing in type 'Bar & Foo' but required in type '{ foo: string; bat: string; }'. Type 'Extract' is not assignable to type '{ foo: string; bat: string; }'. Property 'bat' is missing in type 'Bar & Foo' but required in type '{ foo: string; bat: string; }'. -tests/cases/conformance/types/conditional/conditionalTypes2.ts(76,12): error TS2345: Argument of type 'Extract' is not assignable to parameter of type '{ foo: string; bat: string; }'. +tests/cases/conformance/types/conditional/conditionalTypes2.ts(74,12): error TS2345: Argument of type 'Extract' is not assignable to parameter of type '{ foo: string; bat: string; }'. Property 'bat' is missing in type 'Foo & Bar' but required in type '{ foo: string; bat: string; }'. -tests/cases/conformance/types/conditional/conditionalTypes2.ts(77,12): error TS2345: Argument of type 'Extract2' is not assignable to parameter of type '{ foo: string; bat: string; }'. +tests/cases/conformance/types/conditional/conditionalTypes2.ts(75,12): error TS2345: Argument of type 'Extract2' is not assignable to parameter of type '{ foo: string; bat: string; }'. Type 'T extends Bar ? T : never' is not assignable to type '{ foo: string; bat: string; }'. Type 'Bar & Foo & T' is not assignable to type '{ foo: string; bat: string; }'. -tests/cases/conformance/types/conditional/conditionalTypes2.ts(165,5): error TS2322: Type 'MyElement' is not assignable to type 'MyElement'. -tests/cases/conformance/types/conditional/conditionalTypes2.ts(170,5): error TS2322: Type 'MyAcceptor' is not assignable to type 'MyAcceptor'. -tests/cases/conformance/types/conditional/conditionalTypes2.ts(177,5): error TS2322: Type 'Dist' is not assignable to type 'Aux<{ a: T; }>'. -==== tests/cases/conformance/types/conditional/conditionalTypes2.ts (12 errors) ==== - // #27118: Conditional types are now invariant in the check type. - +==== tests/cases/conformance/types/conditional/conditionalTypes2.ts (7 errors) ==== interface Covariant { foo: T extends string ? T : number; } @@ -46,29 +37,19 @@ tests/cases/conformance/types/conditional/conditionalTypes2.ts(177,5): error TS2 } function f1(a: Covariant, b: Covariant) { - a = b; // Error - ~ -!!! error TS2322: Type 'Covariant' is not assignable to type 'Covariant'. -!!! error TS2322: Types of property 'foo' are incompatible. -!!! error TS2322: Type 'B extends string ? B : number' is not assignable to type 'A extends string ? A : number'. + a = b; b = a; // Error ~ !!! error TS2322: Type 'Covariant' is not assignable to type 'Covariant'. -!!! error TS2322: Types of property 'foo' are incompatible. -!!! error TS2322: Type 'A extends string ? A : number' is not assignable to type 'B extends string ? B : number'. +!!! error TS2322: Type 'A' is not assignable to type 'B'. } function f2(a: Contravariant, b: Contravariant) { a = b; // Error ~ !!! error TS2322: Type 'Contravariant' is not assignable to type 'Contravariant'. -!!! error TS2322: Types of property 'foo' are incompatible. -!!! error TS2322: Type 'B extends string ? keyof B : number' is not assignable to type 'A extends string ? keyof A : number'. - b = a; // Error - ~ -!!! error TS2322: Type 'Contravariant' is not assignable to type 'Contravariant'. -!!! error TS2322: Types of property 'foo' are incompatible. -!!! error TS2322: Type 'A extends string ? keyof A : number' is not assignable to type 'B extends string ? keyof B : number'. +!!! error TS2322: Type 'A' is not assignable to type 'B'. + b = a; } function f3(a: Invariant, b: Invariant) { @@ -77,11 +58,15 @@ tests/cases/conformance/types/conditional/conditionalTypes2.ts(177,5): error TS2 !!! error TS2322: Type 'Invariant' is not assignable to type 'Invariant'. !!! error TS2322: Types of property 'foo' are incompatible. !!! error TS2322: Type 'B extends string ? keyof B : B' is not assignable to type 'A extends string ? keyof A : A'. +!!! error TS2322: Type 'keyof B' is not assignable to type 'keyof A'. +!!! error TS2322: Type 'string | number | symbol' is not assignable to type 'keyof A'. +!!! error TS2322: Type 'string' is not assignable to type 'keyof A'. b = a; // Error ~ !!! error TS2322: Type 'Invariant' is not assignable to type 'Invariant'. !!! error TS2322: Types of property 'foo' are incompatible. !!! error TS2322: Type 'A extends string ? keyof A : A' is not assignable to type 'B extends string ? keyof B : B'. +!!! error TS2322: Type 'A' is not assignable to type 'B'. } // Extract is a T that is known to be a Function @@ -135,13 +120,13 @@ tests/cases/conformance/types/conditional/conditionalTypes2.ts(177,5): error TS2 !!! error TS2345: Property 'bat' is missing in type 'Bar & Foo' but required in type '{ foo: string; bat: string; }'. !!! error TS2345: Type 'Extract' is not assignable to type '{ foo: string; bat: string; }'. !!! error TS2345: Property 'bat' is missing in type 'Bar & Foo' but required in type '{ foo: string; bat: string; }'. -!!! related TS2728 tests/cases/conformance/types/conditional/conditionalTypes2.ts:64:43: 'bat' is declared here. -!!! related TS2728 tests/cases/conformance/types/conditional/conditionalTypes2.ts:64:43: 'bat' is declared here. +!!! related TS2728 tests/cases/conformance/types/conditional/conditionalTypes2.ts:62:43: 'bat' is declared here. +!!! related TS2728 tests/cases/conformance/types/conditional/conditionalTypes2.ts:62:43: 'bat' is declared here. fooBat(y); // Error ~ !!! error TS2345: Argument of type 'Extract' is not assignable to parameter of type '{ foo: string; bat: string; }'. !!! error TS2345: Property 'bat' is missing in type 'Foo & Bar' but required in type '{ foo: string; bat: string; }'. -!!! related TS2728 tests/cases/conformance/types/conditional/conditionalTypes2.ts:64:43: 'bat' is declared here. +!!! related TS2728 tests/cases/conformance/types/conditional/conditionalTypes2.ts:62:43: 'bat' is declared here. fooBat(z); // Error ~ !!! error TS2345: Argument of type 'Extract2' is not assignable to parameter of type '{ foo: string; bat: string; }'. @@ -149,6 +134,38 @@ tests/cases/conformance/types/conditional/conditionalTypes2.ts(177,5): error TS2 !!! error TS2345: Type 'Bar & Foo & T' is not assignable to type '{ foo: string; bat: string; }'. } + // Repros from #22860 + + class Opt { + toVector(): Vector { + return undefined; + } + } + + interface Seq { + tail(): Opt>; + } + + class Vector implements Seq { + tail(): Opt> { + return undefined; + } + partition2(predicate:(v:T)=>v is U): [Vector,Vector>]; + partition2(predicate:(x:T)=>boolean): [Vector,Vector]; + partition2(predicate:(v:T)=>boolean): [Vector,Vector] { + return undefined; + } + } + + interface A1 { + bat: B1>; + } + + interface B1 extends A1 { + bat: B1>; + boom: T extends any ? true : true + } + // Repro from #22899 declare function toString1(value: object | Function): string ; @@ -229,29 +246,4 @@ tests/cases/conformance/types/conditional/conditionalTypes2.ts(177,5): error TS2 }; type PCCA = ProductComplementComplement['a']; type PCCB = ProductComplementComplement['b']; - - // Repros from #27118 - - type MyElement = [A] extends [[infer E]] ? E : never; - function oops(arg: MyElement): MyElement { - return arg; // Unsound, should be error - ~~~~~~~~~~~ -!!! error TS2322: Type 'MyElement' is not assignable to type 'MyElement'. - } - - type MyAcceptor = [A] extends [[infer E]] ? (arg: E) => void : never; - function oops2(arg: MyAcceptor): MyAcceptor { - return arg; // Unsound, should be error - ~~~~~~~~~~~ -!!! error TS2322: Type 'MyAcceptor' is not assignable to type 'MyAcceptor'. - } - - type Dist = T extends number ? number : string; - type Aux = A["a"] extends number ? number : string; - type Nondist = Aux<{a: T}>; - function oops3(arg: Dist): Nondist { - return arg; // Unsound, should be error - ~~~~~~~~~~~ -!!! error TS2322: Type 'Dist' is not assignable to type 'Aux<{ a: T; }>'. - } \ No newline at end of file diff --git a/tests/baselines/reference/conditionalTypes2.js b/tests/baselines/reference/conditionalTypes2.js index c59c996711d..4f4f35e821a 100644 --- a/tests/baselines/reference/conditionalTypes2.js +++ b/tests/baselines/reference/conditionalTypes2.js @@ -1,6 +1,4 @@ //// [conditionalTypes2.ts] -// #27118: Conditional types are now invariant in the check type. - interface Covariant { foo: T extends string ? T : number; } @@ -14,13 +12,13 @@ interface Invariant { } function f1(a: Covariant, b: Covariant) { - a = b; // Error + a = b; b = a; // Error } function f2(a: Contravariant, b: Contravariant) { a = b; // Error - b = a; // Error + b = a; } function f3(a: Invariant, b: Invariant) { @@ -78,6 +76,38 @@ function f21(x: Extract, Bar>, y: Extract, z: E fooBat(z); // Error } +// Repros from #22860 + +class Opt { + toVector(): Vector { + return undefined; + } +} + +interface Seq { + tail(): Opt>; +} + +class Vector implements Seq { + tail(): Opt> { + return undefined; + } + partition2(predicate:(v:T)=>v is U): [Vector,Vector>]; + partition2(predicate:(x:T)=>boolean): [Vector,Vector]; + partition2(predicate:(v:T)=>boolean): [Vector,Vector] { + return undefined; + } +} + +interface A1 { + bat: B1>; +} + +interface B1 extends A1 { + bat: B1>; + boom: T extends any ? true : true +} + // Repro from #22899 declare function toString1(value: object | Function): string ; @@ -158,37 +188,17 @@ type ProductComplementComplement = { }; type PCCA = ProductComplementComplement['a']; type PCCB = ProductComplementComplement['b']; - -// Repros from #27118 - -type MyElement = [A] extends [[infer E]] ? E : never; -function oops(arg: MyElement): MyElement { - return arg; // Unsound, should be error -} - -type MyAcceptor = [A] extends [[infer E]] ? (arg: E) => void : never; -function oops2(arg: MyAcceptor): MyAcceptor { - return arg; // Unsound, should be error -} - -type Dist = T extends number ? number : string; -type Aux = A["a"] extends number ? number : string; -type Nondist = Aux<{a: T}>; -function oops3(arg: Dist): Nondist { - return arg; // Unsound, should be error -} //// [conditionalTypes2.js] "use strict"; -// #27118: Conditional types are now invariant in the check type. function f1(a, b) { - a = b; // Error + a = b; b = a; // Error } function f2(a, b) { a = b; // Error - b = a; // Error + b = a; } function f3(a, b) { a = b; // Error @@ -229,21 +239,32 @@ function f21(x, y, z) { fooBat(y); // Error fooBat(z); // Error } +// Repros from #22860 +var Opt = /** @class */ (function () { + function Opt() { + } + Opt.prototype.toVector = function () { + return undefined; + }; + return Opt; +}()); +var Vector = /** @class */ (function () { + function Vector() { + } + Vector.prototype.tail = function () { + return undefined; + }; + Vector.prototype.partition2 = function (predicate) { + return undefined; + }; + return Vector; +}()); function foo(value) { if (isFunction(value)) { toString1(value); toString2(value); } } -function oops(arg) { - return arg; // Unsound, should be error -} -function oops2(arg) { - return arg; // Unsound, should be error -} -function oops3(arg) { - return arg; // Unsound, should be error -} //// [conditionalTypes2.d.ts] @@ -281,6 +302,24 @@ declare function fooBat(x: { declare type Extract2 = T extends U ? T extends V ? T : never : never; declare function f20(x: Extract, Bar>, y: Extract, z: Extract2): void; declare function f21(x: Extract, Bar>, y: Extract, z: Extract2): void; +declare class Opt { + toVector(): Vector; +} +interface Seq { + tail(): Opt>; +} +declare class Vector implements Seq { + tail(): Opt>; + partition2(predicate: (v: T) => v is U): [Vector, Vector>]; + partition2(predicate: (x: T) => boolean): [Vector, Vector]; +} +interface A1 { + bat: B1>; +} +interface B1 extends A1 { + bat: B1>; + boom: T extends any ? true : true; +} declare function toString1(value: object | Function): string; declare function toString2(value: Function): string; declare function foo(value: T): void; @@ -353,15 +392,3 @@ declare type ProductComplementComplement = { }; declare type PCCA = ProductComplementComplement['a']; declare type PCCB = ProductComplementComplement['b']; -declare type MyElement = [A] extends [[infer E]] ? E : never; -declare function oops(arg: MyElement): MyElement; -declare type MyAcceptor = [A] extends [[infer E]] ? (arg: E) => void : never; -declare function oops2(arg: MyAcceptor): MyAcceptor; -declare type Dist = T extends number ? number : string; -declare type Aux = A["a"] extends number ? number : string; -declare type Nondist = Aux<{ - a: T; -}>; -declare function oops3(arg: Dist): Nondist; diff --git a/tests/baselines/reference/conditionalTypes2.symbols b/tests/baselines/reference/conditionalTypes2.symbols index 7bbf837eece..b164d26e450 100644 --- a/tests/baselines/reference/conditionalTypes2.symbols +++ b/tests/baselines/reference/conditionalTypes2.symbols @@ -1,655 +1,687 @@ === tests/cases/conformance/types/conditional/conditionalTypes2.ts === -// #27118: Conditional types are now invariant in the check type. - interface Covariant { >Covariant : Symbol(Covariant, Decl(conditionalTypes2.ts, 0, 0)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 2, 20)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 0, 20)) foo: T extends string ? T : number; ->foo : Symbol(Covariant.foo, Decl(conditionalTypes2.ts, 2, 24)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 2, 20)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 2, 20)) +>foo : Symbol(Covariant.foo, Decl(conditionalTypes2.ts, 0, 24)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 0, 20)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 0, 20)) } interface Contravariant { ->Contravariant : Symbol(Contravariant, Decl(conditionalTypes2.ts, 4, 1)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 6, 24)) +>Contravariant : Symbol(Contravariant, Decl(conditionalTypes2.ts, 2, 1)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 4, 24)) foo: T extends string ? keyof T : number; ->foo : Symbol(Contravariant.foo, Decl(conditionalTypes2.ts, 6, 28)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 6, 24)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 6, 24)) +>foo : Symbol(Contravariant.foo, Decl(conditionalTypes2.ts, 4, 28)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 4, 24)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 4, 24)) } interface Invariant { ->Invariant : Symbol(Invariant, Decl(conditionalTypes2.ts, 8, 1)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 10, 20)) +>Invariant : Symbol(Invariant, Decl(conditionalTypes2.ts, 6, 1)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 8, 20)) foo: T extends string ? keyof T : T; ->foo : Symbol(Invariant.foo, Decl(conditionalTypes2.ts, 10, 24)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 10, 20)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 10, 20)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 10, 20)) +>foo : Symbol(Invariant.foo, Decl(conditionalTypes2.ts, 8, 24)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 8, 20)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 8, 20)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 8, 20)) } function f1(a: Covariant, b: Covariant) { ->f1 : Symbol(f1, Decl(conditionalTypes2.ts, 12, 1)) ->A : Symbol(A, Decl(conditionalTypes2.ts, 14, 12)) ->B : Symbol(B, Decl(conditionalTypes2.ts, 14, 14)) ->A : Symbol(A, Decl(conditionalTypes2.ts, 14, 12)) ->a : Symbol(a, Decl(conditionalTypes2.ts, 14, 28)) +>f1 : Symbol(f1, Decl(conditionalTypes2.ts, 10, 1)) +>A : Symbol(A, Decl(conditionalTypes2.ts, 12, 12)) +>B : Symbol(B, Decl(conditionalTypes2.ts, 12, 14)) +>A : Symbol(A, Decl(conditionalTypes2.ts, 12, 12)) +>a : Symbol(a, Decl(conditionalTypes2.ts, 12, 28)) >Covariant : Symbol(Covariant, Decl(conditionalTypes2.ts, 0, 0)) ->A : Symbol(A, Decl(conditionalTypes2.ts, 14, 12)) ->b : Symbol(b, Decl(conditionalTypes2.ts, 14, 44)) +>A : Symbol(A, Decl(conditionalTypes2.ts, 12, 12)) +>b : Symbol(b, Decl(conditionalTypes2.ts, 12, 44)) >Covariant : Symbol(Covariant, Decl(conditionalTypes2.ts, 0, 0)) ->B : Symbol(B, Decl(conditionalTypes2.ts, 14, 14)) +>B : Symbol(B, Decl(conditionalTypes2.ts, 12, 14)) - a = b; // Error ->a : Symbol(a, Decl(conditionalTypes2.ts, 14, 28)) ->b : Symbol(b, Decl(conditionalTypes2.ts, 14, 44)) + a = b; +>a : Symbol(a, Decl(conditionalTypes2.ts, 12, 28)) +>b : Symbol(b, Decl(conditionalTypes2.ts, 12, 44)) b = a; // Error ->b : Symbol(b, Decl(conditionalTypes2.ts, 14, 44)) ->a : Symbol(a, Decl(conditionalTypes2.ts, 14, 28)) +>b : Symbol(b, Decl(conditionalTypes2.ts, 12, 44)) +>a : Symbol(a, Decl(conditionalTypes2.ts, 12, 28)) } function f2(a: Contravariant, b: Contravariant) { ->f2 : Symbol(f2, Decl(conditionalTypes2.ts, 17, 1)) ->A : Symbol(A, Decl(conditionalTypes2.ts, 19, 12)) ->B : Symbol(B, Decl(conditionalTypes2.ts, 19, 14)) ->A : Symbol(A, Decl(conditionalTypes2.ts, 19, 12)) ->a : Symbol(a, Decl(conditionalTypes2.ts, 19, 28)) ->Contravariant : Symbol(Contravariant, Decl(conditionalTypes2.ts, 4, 1)) ->A : Symbol(A, Decl(conditionalTypes2.ts, 19, 12)) ->b : Symbol(b, Decl(conditionalTypes2.ts, 19, 48)) ->Contravariant : Symbol(Contravariant, Decl(conditionalTypes2.ts, 4, 1)) ->B : Symbol(B, Decl(conditionalTypes2.ts, 19, 14)) +>f2 : Symbol(f2, Decl(conditionalTypes2.ts, 15, 1)) +>A : Symbol(A, Decl(conditionalTypes2.ts, 17, 12)) +>B : Symbol(B, Decl(conditionalTypes2.ts, 17, 14)) +>A : Symbol(A, Decl(conditionalTypes2.ts, 17, 12)) +>a : Symbol(a, Decl(conditionalTypes2.ts, 17, 28)) +>Contravariant : Symbol(Contravariant, Decl(conditionalTypes2.ts, 2, 1)) +>A : Symbol(A, Decl(conditionalTypes2.ts, 17, 12)) +>b : Symbol(b, Decl(conditionalTypes2.ts, 17, 48)) +>Contravariant : Symbol(Contravariant, Decl(conditionalTypes2.ts, 2, 1)) +>B : Symbol(B, Decl(conditionalTypes2.ts, 17, 14)) a = b; // Error ->a : Symbol(a, Decl(conditionalTypes2.ts, 19, 28)) ->b : Symbol(b, Decl(conditionalTypes2.ts, 19, 48)) +>a : Symbol(a, Decl(conditionalTypes2.ts, 17, 28)) +>b : Symbol(b, Decl(conditionalTypes2.ts, 17, 48)) - b = a; // Error ->b : Symbol(b, Decl(conditionalTypes2.ts, 19, 48)) ->a : Symbol(a, Decl(conditionalTypes2.ts, 19, 28)) + b = a; +>b : Symbol(b, Decl(conditionalTypes2.ts, 17, 48)) +>a : Symbol(a, Decl(conditionalTypes2.ts, 17, 28)) } function f3(a: Invariant, b: Invariant) { ->f3 : Symbol(f3, Decl(conditionalTypes2.ts, 22, 1)) ->A : Symbol(A, Decl(conditionalTypes2.ts, 24, 12)) ->B : Symbol(B, Decl(conditionalTypes2.ts, 24, 14)) ->A : Symbol(A, Decl(conditionalTypes2.ts, 24, 12)) ->a : Symbol(a, Decl(conditionalTypes2.ts, 24, 28)) ->Invariant : Symbol(Invariant, Decl(conditionalTypes2.ts, 8, 1)) ->A : Symbol(A, Decl(conditionalTypes2.ts, 24, 12)) ->b : Symbol(b, Decl(conditionalTypes2.ts, 24, 44)) ->Invariant : Symbol(Invariant, Decl(conditionalTypes2.ts, 8, 1)) ->B : Symbol(B, Decl(conditionalTypes2.ts, 24, 14)) +>f3 : Symbol(f3, Decl(conditionalTypes2.ts, 20, 1)) +>A : Symbol(A, Decl(conditionalTypes2.ts, 22, 12)) +>B : Symbol(B, Decl(conditionalTypes2.ts, 22, 14)) +>A : Symbol(A, Decl(conditionalTypes2.ts, 22, 12)) +>a : Symbol(a, Decl(conditionalTypes2.ts, 22, 28)) +>Invariant : Symbol(Invariant, Decl(conditionalTypes2.ts, 6, 1)) +>A : Symbol(A, Decl(conditionalTypes2.ts, 22, 12)) +>b : Symbol(b, Decl(conditionalTypes2.ts, 22, 44)) +>Invariant : Symbol(Invariant, Decl(conditionalTypes2.ts, 6, 1)) +>B : Symbol(B, Decl(conditionalTypes2.ts, 22, 14)) a = b; // Error ->a : Symbol(a, Decl(conditionalTypes2.ts, 24, 28)) ->b : Symbol(b, Decl(conditionalTypes2.ts, 24, 44)) +>a : Symbol(a, Decl(conditionalTypes2.ts, 22, 28)) +>b : Symbol(b, Decl(conditionalTypes2.ts, 22, 44)) b = a; // Error ->b : Symbol(b, Decl(conditionalTypes2.ts, 24, 44)) ->a : Symbol(a, Decl(conditionalTypes2.ts, 24, 28)) +>b : Symbol(b, Decl(conditionalTypes2.ts, 22, 44)) +>a : Symbol(a, Decl(conditionalTypes2.ts, 22, 28)) } // Extract is a T that is known to be a Function function isFunction(value: T): value is Extract { ->isFunction : Symbol(isFunction, Decl(conditionalTypes2.ts, 27, 1)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 30, 20)) ->value : Symbol(value, Decl(conditionalTypes2.ts, 30, 23)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 30, 20)) ->value : Symbol(value, Decl(conditionalTypes2.ts, 30, 23)) +>isFunction : Symbol(isFunction, Decl(conditionalTypes2.ts, 25, 1)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 28, 20)) +>value : Symbol(value, Decl(conditionalTypes2.ts, 28, 23)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 28, 20)) +>value : Symbol(value, Decl(conditionalTypes2.ts, 28, 23)) >Extract : Symbol(Extract, Decl(lib.es5.d.ts, --, --)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 30, 20)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 28, 20)) >Function : Symbol(Function, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) return typeof value === "function"; ->value : Symbol(value, Decl(conditionalTypes2.ts, 30, 23)) +>value : Symbol(value, Decl(conditionalTypes2.ts, 28, 23)) } function getFunction(item: T) { ->getFunction : Symbol(getFunction, Decl(conditionalTypes2.ts, 32, 1)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 34, 21)) ->item : Symbol(item, Decl(conditionalTypes2.ts, 34, 24)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 34, 21)) +>getFunction : Symbol(getFunction, Decl(conditionalTypes2.ts, 30, 1)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 32, 21)) +>item : Symbol(item, Decl(conditionalTypes2.ts, 32, 24)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 32, 21)) if (isFunction(item)) { ->isFunction : Symbol(isFunction, Decl(conditionalTypes2.ts, 27, 1)) ->item : Symbol(item, Decl(conditionalTypes2.ts, 34, 24)) +>isFunction : Symbol(isFunction, Decl(conditionalTypes2.ts, 25, 1)) +>item : Symbol(item, Decl(conditionalTypes2.ts, 32, 24)) return item; ->item : Symbol(item, Decl(conditionalTypes2.ts, 34, 24)) +>item : Symbol(item, Decl(conditionalTypes2.ts, 32, 24)) } throw new Error(); >Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) } function f10(x: T) { ->f10 : Symbol(f10, Decl(conditionalTypes2.ts, 39, 1)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 41, 13)) ->x : Symbol(x, Decl(conditionalTypes2.ts, 41, 16)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 41, 13)) +>f10 : Symbol(f10, Decl(conditionalTypes2.ts, 37, 1)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 39, 13)) +>x : Symbol(x, Decl(conditionalTypes2.ts, 39, 16)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 39, 13)) if (isFunction(x)) { ->isFunction : Symbol(isFunction, Decl(conditionalTypes2.ts, 27, 1)) ->x : Symbol(x, Decl(conditionalTypes2.ts, 41, 16)) +>isFunction : Symbol(isFunction, Decl(conditionalTypes2.ts, 25, 1)) +>x : Symbol(x, Decl(conditionalTypes2.ts, 39, 16)) const f: Function = x; ->f : Symbol(f, Decl(conditionalTypes2.ts, 43, 13)) +>f : Symbol(f, Decl(conditionalTypes2.ts, 41, 13)) >Function : Symbol(Function, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) ->x : Symbol(x, Decl(conditionalTypes2.ts, 41, 16)) +>x : Symbol(x, Decl(conditionalTypes2.ts, 39, 16)) const t: T = x; ->t : Symbol(t, Decl(conditionalTypes2.ts, 44, 13)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 41, 13)) ->x : Symbol(x, Decl(conditionalTypes2.ts, 41, 16)) +>t : Symbol(t, Decl(conditionalTypes2.ts, 42, 13)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 39, 13)) +>x : Symbol(x, Decl(conditionalTypes2.ts, 39, 16)) } } function f11(x: string | (() => string) | undefined) { ->f11 : Symbol(f11, Decl(conditionalTypes2.ts, 46, 1)) ->x : Symbol(x, Decl(conditionalTypes2.ts, 48, 13)) +>f11 : Symbol(f11, Decl(conditionalTypes2.ts, 44, 1)) +>x : Symbol(x, Decl(conditionalTypes2.ts, 46, 13)) if (isFunction(x)) { ->isFunction : Symbol(isFunction, Decl(conditionalTypes2.ts, 27, 1)) ->x : Symbol(x, Decl(conditionalTypes2.ts, 48, 13)) +>isFunction : Symbol(isFunction, Decl(conditionalTypes2.ts, 25, 1)) +>x : Symbol(x, Decl(conditionalTypes2.ts, 46, 13)) x(); ->x : Symbol(x, Decl(conditionalTypes2.ts, 48, 13)) +>x : Symbol(x, Decl(conditionalTypes2.ts, 46, 13)) } } function f12(x: string | (() => string) | undefined) { ->f12 : Symbol(f12, Decl(conditionalTypes2.ts, 52, 1)) ->x : Symbol(x, Decl(conditionalTypes2.ts, 54, 13)) +>f12 : Symbol(f12, Decl(conditionalTypes2.ts, 50, 1)) +>x : Symbol(x, Decl(conditionalTypes2.ts, 52, 13)) const f = getFunction(x); // () => string ->f : Symbol(f, Decl(conditionalTypes2.ts, 55, 9)) ->getFunction : Symbol(getFunction, Decl(conditionalTypes2.ts, 32, 1)) ->x : Symbol(x, Decl(conditionalTypes2.ts, 54, 13)) +>f : Symbol(f, Decl(conditionalTypes2.ts, 53, 9)) +>getFunction : Symbol(getFunction, Decl(conditionalTypes2.ts, 30, 1)) +>x : Symbol(x, Decl(conditionalTypes2.ts, 52, 13)) f(); ->f : Symbol(f, Decl(conditionalTypes2.ts, 55, 9)) +>f : Symbol(f, Decl(conditionalTypes2.ts, 53, 9)) } type Foo = { foo: string }; ->Foo : Symbol(Foo, Decl(conditionalTypes2.ts, 57, 1)) ->foo : Symbol(foo, Decl(conditionalTypes2.ts, 59, 12)) +>Foo : Symbol(Foo, Decl(conditionalTypes2.ts, 55, 1)) +>foo : Symbol(foo, Decl(conditionalTypes2.ts, 57, 12)) type Bar = { bar: string }; ->Bar : Symbol(Bar, Decl(conditionalTypes2.ts, 59, 27)) ->bar : Symbol(bar, Decl(conditionalTypes2.ts, 60, 12)) +>Bar : Symbol(Bar, Decl(conditionalTypes2.ts, 57, 27)) +>bar : Symbol(bar, Decl(conditionalTypes2.ts, 58, 12)) declare function fooBar(x: { foo: string, bar: string }): void; ->fooBar : Symbol(fooBar, Decl(conditionalTypes2.ts, 60, 27)) ->x : Symbol(x, Decl(conditionalTypes2.ts, 62, 24)) ->foo : Symbol(foo, Decl(conditionalTypes2.ts, 62, 28)) ->bar : Symbol(bar, Decl(conditionalTypes2.ts, 62, 41)) +>fooBar : Symbol(fooBar, Decl(conditionalTypes2.ts, 58, 27)) +>x : Symbol(x, Decl(conditionalTypes2.ts, 60, 24)) +>foo : Symbol(foo, Decl(conditionalTypes2.ts, 60, 28)) +>bar : Symbol(bar, Decl(conditionalTypes2.ts, 60, 41)) declare function fooBat(x: { foo: string, bat: string }): void; ->fooBat : Symbol(fooBat, Decl(conditionalTypes2.ts, 62, 63)) ->x : Symbol(x, Decl(conditionalTypes2.ts, 63, 24)) ->foo : Symbol(foo, Decl(conditionalTypes2.ts, 63, 28)) ->bat : Symbol(bat, Decl(conditionalTypes2.ts, 63, 41)) +>fooBat : Symbol(fooBat, Decl(conditionalTypes2.ts, 60, 63)) +>x : Symbol(x, Decl(conditionalTypes2.ts, 61, 24)) +>foo : Symbol(foo, Decl(conditionalTypes2.ts, 61, 28)) +>bat : Symbol(bat, Decl(conditionalTypes2.ts, 61, 41)) type Extract2 = T extends U ? T extends V ? T : never : never; ->Extract2 : Symbol(Extract2, Decl(conditionalTypes2.ts, 63, 63)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 65, 14)) ->U : Symbol(U, Decl(conditionalTypes2.ts, 65, 16)) ->V : Symbol(V, Decl(conditionalTypes2.ts, 65, 19)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 65, 14)) ->U : Symbol(U, Decl(conditionalTypes2.ts, 65, 16)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 65, 14)) ->V : Symbol(V, Decl(conditionalTypes2.ts, 65, 19)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 65, 14)) +>Extract2 : Symbol(Extract2, Decl(conditionalTypes2.ts, 61, 63)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 63, 14)) +>U : Symbol(U, Decl(conditionalTypes2.ts, 63, 16)) +>V : Symbol(V, Decl(conditionalTypes2.ts, 63, 19)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 63, 14)) +>U : Symbol(U, Decl(conditionalTypes2.ts, 63, 16)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 63, 14)) +>V : Symbol(V, Decl(conditionalTypes2.ts, 63, 19)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 63, 14)) function f20(x: Extract, Bar>, y: Extract, z: Extract2) { ->f20 : Symbol(f20, Decl(conditionalTypes2.ts, 65, 71)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 67, 13)) ->x : Symbol(x, Decl(conditionalTypes2.ts, 67, 16)) +>f20 : Symbol(f20, Decl(conditionalTypes2.ts, 63, 71)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 65, 13)) +>x : Symbol(x, Decl(conditionalTypes2.ts, 65, 16)) >Extract : Symbol(Extract, Decl(lib.es5.d.ts, --, --)) >Extract : Symbol(Extract, Decl(lib.es5.d.ts, --, --)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 67, 13)) ->Foo : Symbol(Foo, Decl(conditionalTypes2.ts, 57, 1)) ->Bar : Symbol(Bar, Decl(conditionalTypes2.ts, 59, 27)) ->y : Symbol(y, Decl(conditionalTypes2.ts, 67, 49)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 65, 13)) +>Foo : Symbol(Foo, Decl(conditionalTypes2.ts, 55, 1)) +>Bar : Symbol(Bar, Decl(conditionalTypes2.ts, 57, 27)) +>y : Symbol(y, Decl(conditionalTypes2.ts, 65, 49)) >Extract : Symbol(Extract, Decl(lib.es5.d.ts, --, --)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 67, 13)) ->Foo : Symbol(Foo, Decl(conditionalTypes2.ts, 57, 1)) ->Bar : Symbol(Bar, Decl(conditionalTypes2.ts, 59, 27)) ->z : Symbol(z, Decl(conditionalTypes2.ts, 67, 75)) ->Extract2 : Symbol(Extract2, Decl(conditionalTypes2.ts, 63, 63)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 67, 13)) ->Foo : Symbol(Foo, Decl(conditionalTypes2.ts, 57, 1)) ->Bar : Symbol(Bar, Decl(conditionalTypes2.ts, 59, 27)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 65, 13)) +>Foo : Symbol(Foo, Decl(conditionalTypes2.ts, 55, 1)) +>Bar : Symbol(Bar, Decl(conditionalTypes2.ts, 57, 27)) +>z : Symbol(z, Decl(conditionalTypes2.ts, 65, 75)) +>Extract2 : Symbol(Extract2, Decl(conditionalTypes2.ts, 61, 63)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 65, 13)) +>Foo : Symbol(Foo, Decl(conditionalTypes2.ts, 55, 1)) +>Bar : Symbol(Bar, Decl(conditionalTypes2.ts, 57, 27)) fooBar(x); ->fooBar : Symbol(fooBar, Decl(conditionalTypes2.ts, 60, 27)) ->x : Symbol(x, Decl(conditionalTypes2.ts, 67, 16)) +>fooBar : Symbol(fooBar, Decl(conditionalTypes2.ts, 58, 27)) +>x : Symbol(x, Decl(conditionalTypes2.ts, 65, 16)) fooBar(y); ->fooBar : Symbol(fooBar, Decl(conditionalTypes2.ts, 60, 27)) ->y : Symbol(y, Decl(conditionalTypes2.ts, 67, 49)) +>fooBar : Symbol(fooBar, Decl(conditionalTypes2.ts, 58, 27)) +>y : Symbol(y, Decl(conditionalTypes2.ts, 65, 49)) fooBar(z); ->fooBar : Symbol(fooBar, Decl(conditionalTypes2.ts, 60, 27)) ->z : Symbol(z, Decl(conditionalTypes2.ts, 67, 75)) +>fooBar : Symbol(fooBar, Decl(conditionalTypes2.ts, 58, 27)) +>z : Symbol(z, Decl(conditionalTypes2.ts, 65, 75)) } function f21(x: Extract, Bar>, y: Extract, z: Extract2) { ->f21 : Symbol(f21, Decl(conditionalTypes2.ts, 71, 1)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 73, 13)) ->x : Symbol(x, Decl(conditionalTypes2.ts, 73, 16)) +>f21 : Symbol(f21, Decl(conditionalTypes2.ts, 69, 1)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 71, 13)) +>x : Symbol(x, Decl(conditionalTypes2.ts, 71, 16)) >Extract : Symbol(Extract, Decl(lib.es5.d.ts, --, --)) >Extract : Symbol(Extract, Decl(lib.es5.d.ts, --, --)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 73, 13)) ->Foo : Symbol(Foo, Decl(conditionalTypes2.ts, 57, 1)) ->Bar : Symbol(Bar, Decl(conditionalTypes2.ts, 59, 27)) ->y : Symbol(y, Decl(conditionalTypes2.ts, 73, 49)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 71, 13)) +>Foo : Symbol(Foo, Decl(conditionalTypes2.ts, 55, 1)) +>Bar : Symbol(Bar, Decl(conditionalTypes2.ts, 57, 27)) +>y : Symbol(y, Decl(conditionalTypes2.ts, 71, 49)) >Extract : Symbol(Extract, Decl(lib.es5.d.ts, --, --)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 73, 13)) ->Foo : Symbol(Foo, Decl(conditionalTypes2.ts, 57, 1)) ->Bar : Symbol(Bar, Decl(conditionalTypes2.ts, 59, 27)) ->z : Symbol(z, Decl(conditionalTypes2.ts, 73, 75)) ->Extract2 : Symbol(Extract2, Decl(conditionalTypes2.ts, 63, 63)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 73, 13)) ->Foo : Symbol(Foo, Decl(conditionalTypes2.ts, 57, 1)) ->Bar : Symbol(Bar, Decl(conditionalTypes2.ts, 59, 27)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 71, 13)) +>Foo : Symbol(Foo, Decl(conditionalTypes2.ts, 55, 1)) +>Bar : Symbol(Bar, Decl(conditionalTypes2.ts, 57, 27)) +>z : Symbol(z, Decl(conditionalTypes2.ts, 71, 75)) +>Extract2 : Symbol(Extract2, Decl(conditionalTypes2.ts, 61, 63)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 71, 13)) +>Foo : Symbol(Foo, Decl(conditionalTypes2.ts, 55, 1)) +>Bar : Symbol(Bar, Decl(conditionalTypes2.ts, 57, 27)) fooBat(x); // Error ->fooBat : Symbol(fooBat, Decl(conditionalTypes2.ts, 62, 63)) ->x : Symbol(x, Decl(conditionalTypes2.ts, 73, 16)) +>fooBat : Symbol(fooBat, Decl(conditionalTypes2.ts, 60, 63)) +>x : Symbol(x, Decl(conditionalTypes2.ts, 71, 16)) fooBat(y); // Error ->fooBat : Symbol(fooBat, Decl(conditionalTypes2.ts, 62, 63)) ->y : Symbol(y, Decl(conditionalTypes2.ts, 73, 49)) +>fooBat : Symbol(fooBat, Decl(conditionalTypes2.ts, 60, 63)) +>y : Symbol(y, Decl(conditionalTypes2.ts, 71, 49)) fooBat(z); // Error ->fooBat : Symbol(fooBat, Decl(conditionalTypes2.ts, 62, 63)) ->z : Symbol(z, Decl(conditionalTypes2.ts, 73, 75)) +>fooBat : Symbol(fooBat, Decl(conditionalTypes2.ts, 60, 63)) +>z : Symbol(z, Decl(conditionalTypes2.ts, 71, 75)) +} + +// Repros from #22860 + +class Opt { +>Opt : Symbol(Opt, Decl(conditionalTypes2.ts, 75, 1)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 79, 10)) + + toVector(): Vector { +>toVector : Symbol(Opt.toVector, Decl(conditionalTypes2.ts, 79, 14)) +>Vector : Symbol(Vector, Decl(conditionalTypes2.ts, 87, 1)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 79, 10)) + + return undefined; +>undefined : Symbol(undefined) + } +} + +interface Seq { +>Seq : Symbol(Seq, Decl(conditionalTypes2.ts, 83, 1)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 85, 14)) + + tail(): Opt>; +>tail : Symbol(Seq.tail, Decl(conditionalTypes2.ts, 85, 18)) +>Opt : Symbol(Opt, Decl(conditionalTypes2.ts, 75, 1)) +>Seq : Symbol(Seq, Decl(conditionalTypes2.ts, 83, 1)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 85, 14)) +} + +class Vector implements Seq { +>Vector : Symbol(Vector, Decl(conditionalTypes2.ts, 87, 1)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 89, 13)) +>Seq : Symbol(Seq, Decl(conditionalTypes2.ts, 83, 1)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 89, 13)) + + tail(): Opt> { +>tail : Symbol(Vector.tail, Decl(conditionalTypes2.ts, 89, 35)) +>Opt : Symbol(Opt, Decl(conditionalTypes2.ts, 75, 1)) +>Vector : Symbol(Vector, Decl(conditionalTypes2.ts, 87, 1)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 89, 13)) + + return undefined; +>undefined : Symbol(undefined) + } + partition2(predicate:(v:T)=>v is U): [Vector,Vector>]; +>partition2 : Symbol(Vector.partition2, Decl(conditionalTypes2.ts, 92, 5), Decl(conditionalTypes2.ts, 93, 88), Decl(conditionalTypes2.ts, 94, 64)) +>U : Symbol(U, Decl(conditionalTypes2.ts, 93, 15)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 89, 13)) +>predicate : Symbol(predicate, Decl(conditionalTypes2.ts, 93, 28)) +>v : Symbol(v, Decl(conditionalTypes2.ts, 93, 39)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 89, 13)) +>v : Symbol(v, Decl(conditionalTypes2.ts, 93, 39)) +>U : Symbol(U, Decl(conditionalTypes2.ts, 93, 15)) +>Vector : Symbol(Vector, Decl(conditionalTypes2.ts, 87, 1)) +>U : Symbol(U, Decl(conditionalTypes2.ts, 93, 15)) +>Vector : Symbol(Vector, Decl(conditionalTypes2.ts, 87, 1)) +>Exclude : Symbol(Exclude, Decl(lib.es5.d.ts, --, --)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 89, 13)) +>U : Symbol(U, Decl(conditionalTypes2.ts, 93, 15)) + + partition2(predicate:(x:T)=>boolean): [Vector,Vector]; +>partition2 : Symbol(Vector.partition2, Decl(conditionalTypes2.ts, 92, 5), Decl(conditionalTypes2.ts, 93, 88), Decl(conditionalTypes2.ts, 94, 64)) +>predicate : Symbol(predicate, Decl(conditionalTypes2.ts, 94, 15)) +>x : Symbol(x, Decl(conditionalTypes2.ts, 94, 26)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 89, 13)) +>Vector : Symbol(Vector, Decl(conditionalTypes2.ts, 87, 1)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 89, 13)) +>Vector : Symbol(Vector, Decl(conditionalTypes2.ts, 87, 1)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 89, 13)) + + partition2(predicate:(v:T)=>boolean): [Vector,Vector] { +>partition2 : Symbol(Vector.partition2, Decl(conditionalTypes2.ts, 92, 5), Decl(conditionalTypes2.ts, 93, 88), Decl(conditionalTypes2.ts, 94, 64)) +>U : Symbol(U, Decl(conditionalTypes2.ts, 95, 15)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 89, 13)) +>predicate : Symbol(predicate, Decl(conditionalTypes2.ts, 95, 28)) +>v : Symbol(v, Decl(conditionalTypes2.ts, 95, 39)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 89, 13)) +>Vector : Symbol(Vector, Decl(conditionalTypes2.ts, 87, 1)) +>U : Symbol(U, Decl(conditionalTypes2.ts, 95, 15)) +>Vector : Symbol(Vector, Decl(conditionalTypes2.ts, 87, 1)) + + return undefined; +>undefined : Symbol(undefined) + } +} + +interface A1 { +>A1 : Symbol(A1, Decl(conditionalTypes2.ts, 98, 1)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 100, 13)) + + bat: B1>; +>bat : Symbol(A1.bat, Decl(conditionalTypes2.ts, 100, 17)) +>B1 : Symbol(B1, Decl(conditionalTypes2.ts, 102, 1)) +>A1 : Symbol(A1, Decl(conditionalTypes2.ts, 98, 1)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 100, 13)) +} + +interface B1 extends A1 { +>B1 : Symbol(B1, Decl(conditionalTypes2.ts, 102, 1)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 104, 13)) +>A1 : Symbol(A1, Decl(conditionalTypes2.ts, 98, 1)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 104, 13)) + + bat: B1>; +>bat : Symbol(B1.bat, Decl(conditionalTypes2.ts, 104, 31)) +>B1 : Symbol(B1, Decl(conditionalTypes2.ts, 102, 1)) +>B1 : Symbol(B1, Decl(conditionalTypes2.ts, 102, 1)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 104, 13)) + + boom: T extends any ? true : true +>boom : Symbol(B1.boom, Decl(conditionalTypes2.ts, 105, 19)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 104, 13)) } // Repro from #22899 declare function toString1(value: object | Function): string ; ->toString1 : Symbol(toString1, Decl(conditionalTypes2.ts, 77, 1)) ->value : Symbol(value, Decl(conditionalTypes2.ts, 81, 27)) +>toString1 : Symbol(toString1, Decl(conditionalTypes2.ts, 107, 1)) +>value : Symbol(value, Decl(conditionalTypes2.ts, 111, 27)) >Function : Symbol(Function, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) declare function toString2(value: Function): string ; ->toString2 : Symbol(toString2, Decl(conditionalTypes2.ts, 81, 62)) ->value : Symbol(value, Decl(conditionalTypes2.ts, 82, 27)) +>toString2 : Symbol(toString2, Decl(conditionalTypes2.ts, 111, 62)) +>value : Symbol(value, Decl(conditionalTypes2.ts, 112, 27)) >Function : Symbol(Function, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) function foo(value: T) { ->foo : Symbol(foo, Decl(conditionalTypes2.ts, 82, 53)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 84, 13)) ->value : Symbol(value, Decl(conditionalTypes2.ts, 84, 16)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 84, 13)) +>foo : Symbol(foo, Decl(conditionalTypes2.ts, 112, 53)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 114, 13)) +>value : Symbol(value, Decl(conditionalTypes2.ts, 114, 16)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 114, 13)) if (isFunction(value)) { ->isFunction : Symbol(isFunction, Decl(conditionalTypes2.ts, 27, 1)) ->value : Symbol(value, Decl(conditionalTypes2.ts, 84, 16)) +>isFunction : Symbol(isFunction, Decl(conditionalTypes2.ts, 25, 1)) +>value : Symbol(value, Decl(conditionalTypes2.ts, 114, 16)) toString1(value); ->toString1 : Symbol(toString1, Decl(conditionalTypes2.ts, 77, 1)) ->value : Symbol(value, Decl(conditionalTypes2.ts, 84, 16)) +>toString1 : Symbol(toString1, Decl(conditionalTypes2.ts, 107, 1)) +>value : Symbol(value, Decl(conditionalTypes2.ts, 114, 16)) toString2(value); ->toString2 : Symbol(toString2, Decl(conditionalTypes2.ts, 81, 62)) ->value : Symbol(value, Decl(conditionalTypes2.ts, 84, 16)) +>toString2 : Symbol(toString2, Decl(conditionalTypes2.ts, 111, 62)) +>value : Symbol(value, Decl(conditionalTypes2.ts, 114, 16)) } } // Repro from #23052 type A = ->A : Symbol(A, Decl(conditionalTypes2.ts, 89, 1)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 93, 7)) ->V : Symbol(V, Decl(conditionalTypes2.ts, 93, 9)) ->E : Symbol(E, Decl(conditionalTypes2.ts, 93, 12)) +>A : Symbol(A, Decl(conditionalTypes2.ts, 119, 1)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 123, 7)) +>V : Symbol(V, Decl(conditionalTypes2.ts, 123, 9)) +>E : Symbol(E, Decl(conditionalTypes2.ts, 123, 12)) T extends object ->T : Symbol(T, Decl(conditionalTypes2.ts, 93, 7)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 123, 7)) ? { [Q in { [P in keyof T]: T[P] extends V ? P : P; }[keyof T]]: A; } ->Q : Symbol(Q, Decl(conditionalTypes2.ts, 95, 9)) ->P : Symbol(P, Decl(conditionalTypes2.ts, 95, 17)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 93, 7)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 93, 7)) ->P : Symbol(P, Decl(conditionalTypes2.ts, 95, 17)) ->V : Symbol(V, Decl(conditionalTypes2.ts, 93, 9)) ->P : Symbol(P, Decl(conditionalTypes2.ts, 95, 17)) ->P : Symbol(P, Decl(conditionalTypes2.ts, 95, 17)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 93, 7)) ->A : Symbol(A, Decl(conditionalTypes2.ts, 89, 1)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 93, 7)) ->Q : Symbol(Q, Decl(conditionalTypes2.ts, 95, 9)) ->V : Symbol(V, Decl(conditionalTypes2.ts, 93, 9)) ->E : Symbol(E, Decl(conditionalTypes2.ts, 93, 12)) +>Q : Symbol(Q, Decl(conditionalTypes2.ts, 125, 9)) +>P : Symbol(P, Decl(conditionalTypes2.ts, 125, 17)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 123, 7)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 123, 7)) +>P : Symbol(P, Decl(conditionalTypes2.ts, 125, 17)) +>V : Symbol(V, Decl(conditionalTypes2.ts, 123, 9)) +>P : Symbol(P, Decl(conditionalTypes2.ts, 125, 17)) +>P : Symbol(P, Decl(conditionalTypes2.ts, 125, 17)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 123, 7)) +>A : Symbol(A, Decl(conditionalTypes2.ts, 119, 1)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 123, 7)) +>Q : Symbol(Q, Decl(conditionalTypes2.ts, 125, 9)) +>V : Symbol(V, Decl(conditionalTypes2.ts, 123, 9)) +>E : Symbol(E, Decl(conditionalTypes2.ts, 123, 12)) : T extends V ? T : never; ->T : Symbol(T, Decl(conditionalTypes2.ts, 93, 7)) ->V : Symbol(V, Decl(conditionalTypes2.ts, 93, 9)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 93, 7)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 123, 7)) +>V : Symbol(V, Decl(conditionalTypes2.ts, 123, 9)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 123, 7)) type B = ->B : Symbol(B, Decl(conditionalTypes2.ts, 96, 30)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 98, 7)) ->V : Symbol(V, Decl(conditionalTypes2.ts, 98, 9)) +>B : Symbol(B, Decl(conditionalTypes2.ts, 126, 30)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 128, 7)) +>V : Symbol(V, Decl(conditionalTypes2.ts, 128, 9)) T extends object ->T : Symbol(T, Decl(conditionalTypes2.ts, 98, 7)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 128, 7)) ? { [Q in { [P in keyof T]: T[P] extends V ? P : P; }[keyof T]]: B; } ->Q : Symbol(Q, Decl(conditionalTypes2.ts, 100, 9)) ->P : Symbol(P, Decl(conditionalTypes2.ts, 100, 17)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 98, 7)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 98, 7)) ->P : Symbol(P, Decl(conditionalTypes2.ts, 100, 17)) ->V : Symbol(V, Decl(conditionalTypes2.ts, 98, 9)) ->P : Symbol(P, Decl(conditionalTypes2.ts, 100, 17)) ->P : Symbol(P, Decl(conditionalTypes2.ts, 100, 17)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 98, 7)) ->B : Symbol(B, Decl(conditionalTypes2.ts, 96, 30)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 98, 7)) ->Q : Symbol(Q, Decl(conditionalTypes2.ts, 100, 9)) ->V : Symbol(V, Decl(conditionalTypes2.ts, 98, 9)) +>Q : Symbol(Q, Decl(conditionalTypes2.ts, 130, 9)) +>P : Symbol(P, Decl(conditionalTypes2.ts, 130, 17)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 128, 7)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 128, 7)) +>P : Symbol(P, Decl(conditionalTypes2.ts, 130, 17)) +>V : Symbol(V, Decl(conditionalTypes2.ts, 128, 9)) +>P : Symbol(P, Decl(conditionalTypes2.ts, 130, 17)) +>P : Symbol(P, Decl(conditionalTypes2.ts, 130, 17)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 128, 7)) +>B : Symbol(B, Decl(conditionalTypes2.ts, 126, 30)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 128, 7)) +>Q : Symbol(Q, Decl(conditionalTypes2.ts, 130, 9)) +>V : Symbol(V, Decl(conditionalTypes2.ts, 128, 9)) : T extends V ? T : never; ->T : Symbol(T, Decl(conditionalTypes2.ts, 98, 7)) ->V : Symbol(V, Decl(conditionalTypes2.ts, 98, 9)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 98, 7)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 128, 7)) +>V : Symbol(V, Decl(conditionalTypes2.ts, 128, 9)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 128, 7)) type C = ->C : Symbol(C, Decl(conditionalTypes2.ts, 101, 30)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 103, 7)) ->V : Symbol(V, Decl(conditionalTypes2.ts, 103, 9)) ->E : Symbol(E, Decl(conditionalTypes2.ts, 103, 12)) +>C : Symbol(C, Decl(conditionalTypes2.ts, 131, 30)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 133, 7)) +>V : Symbol(V, Decl(conditionalTypes2.ts, 133, 9)) +>E : Symbol(E, Decl(conditionalTypes2.ts, 133, 12)) { [Q in { [P in keyof T]: T[P] extends V ? P : P; }[keyof T]]: C; }; ->Q : Symbol(Q, Decl(conditionalTypes2.ts, 104, 5)) ->P : Symbol(P, Decl(conditionalTypes2.ts, 104, 13)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 103, 7)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 103, 7)) ->P : Symbol(P, Decl(conditionalTypes2.ts, 104, 13)) ->V : Symbol(V, Decl(conditionalTypes2.ts, 103, 9)) ->P : Symbol(P, Decl(conditionalTypes2.ts, 104, 13)) ->P : Symbol(P, Decl(conditionalTypes2.ts, 104, 13)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 103, 7)) ->C : Symbol(C, Decl(conditionalTypes2.ts, 101, 30)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 103, 7)) ->Q : Symbol(Q, Decl(conditionalTypes2.ts, 104, 5)) ->V : Symbol(V, Decl(conditionalTypes2.ts, 103, 9)) ->E : Symbol(E, Decl(conditionalTypes2.ts, 103, 12)) +>Q : Symbol(Q, Decl(conditionalTypes2.ts, 134, 5)) +>P : Symbol(P, Decl(conditionalTypes2.ts, 134, 13)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 133, 7)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 133, 7)) +>P : Symbol(P, Decl(conditionalTypes2.ts, 134, 13)) +>V : Symbol(V, Decl(conditionalTypes2.ts, 133, 9)) +>P : Symbol(P, Decl(conditionalTypes2.ts, 134, 13)) +>P : Symbol(P, Decl(conditionalTypes2.ts, 134, 13)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 133, 7)) +>C : Symbol(C, Decl(conditionalTypes2.ts, 131, 30)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 133, 7)) +>Q : Symbol(Q, Decl(conditionalTypes2.ts, 134, 5)) +>V : Symbol(V, Decl(conditionalTypes2.ts, 133, 9)) +>E : Symbol(E, Decl(conditionalTypes2.ts, 133, 12)) // Repro from #23100 type A2 = ->A2 : Symbol(A2, Decl(conditionalTypes2.ts, 104, 82)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 108, 8)) ->V : Symbol(V, Decl(conditionalTypes2.ts, 108, 10)) ->E : Symbol(E, Decl(conditionalTypes2.ts, 108, 13)) +>A2 : Symbol(A2, Decl(conditionalTypes2.ts, 134, 82)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 138, 8)) +>V : Symbol(V, Decl(conditionalTypes2.ts, 138, 10)) +>E : Symbol(E, Decl(conditionalTypes2.ts, 138, 13)) T extends object ? T extends any[] ? T : { [Q in keyof T]: A2; } : T; ->T : Symbol(T, Decl(conditionalTypes2.ts, 108, 8)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 108, 8)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 108, 8)) ->Q : Symbol(Q, Decl(conditionalTypes2.ts, 109, 48)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 108, 8)) ->A2 : Symbol(A2, Decl(conditionalTypes2.ts, 104, 82)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 108, 8)) ->Q : Symbol(Q, Decl(conditionalTypes2.ts, 109, 48)) ->V : Symbol(V, Decl(conditionalTypes2.ts, 108, 10)) ->E : Symbol(E, Decl(conditionalTypes2.ts, 108, 13)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 108, 8)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 138, 8)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 138, 8)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 138, 8)) +>Q : Symbol(Q, Decl(conditionalTypes2.ts, 139, 48)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 138, 8)) +>A2 : Symbol(A2, Decl(conditionalTypes2.ts, 134, 82)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 138, 8)) +>Q : Symbol(Q, Decl(conditionalTypes2.ts, 139, 48)) +>V : Symbol(V, Decl(conditionalTypes2.ts, 138, 10)) +>E : Symbol(E, Decl(conditionalTypes2.ts, 138, 13)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 138, 8)) type B2 = ->B2 : Symbol(B2, Decl(conditionalTypes2.ts, 109, 85)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 111, 8)) ->V : Symbol(V, Decl(conditionalTypes2.ts, 111, 10)) +>B2 : Symbol(B2, Decl(conditionalTypes2.ts, 139, 85)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 141, 8)) +>V : Symbol(V, Decl(conditionalTypes2.ts, 141, 10)) T extends object ? T extends any[] ? T : { [Q in keyof T]: B2; } : T; ->T : Symbol(T, Decl(conditionalTypes2.ts, 111, 8)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 111, 8)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 111, 8)) ->Q : Symbol(Q, Decl(conditionalTypes2.ts, 112, 48)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 111, 8)) ->B2 : Symbol(B2, Decl(conditionalTypes2.ts, 109, 85)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 111, 8)) ->Q : Symbol(Q, Decl(conditionalTypes2.ts, 112, 48)) ->V : Symbol(V, Decl(conditionalTypes2.ts, 111, 10)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 111, 8)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 141, 8)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 141, 8)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 141, 8)) +>Q : Symbol(Q, Decl(conditionalTypes2.ts, 142, 48)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 141, 8)) +>B2 : Symbol(B2, Decl(conditionalTypes2.ts, 139, 85)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 141, 8)) +>Q : Symbol(Q, Decl(conditionalTypes2.ts, 142, 48)) +>V : Symbol(V, Decl(conditionalTypes2.ts, 141, 10)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 141, 8)) type C2 = ->C2 : Symbol(C2, Decl(conditionalTypes2.ts, 112, 82)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 114, 8)) ->V : Symbol(V, Decl(conditionalTypes2.ts, 114, 10)) ->E : Symbol(E, Decl(conditionalTypes2.ts, 114, 13)) +>C2 : Symbol(C2, Decl(conditionalTypes2.ts, 142, 82)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 144, 8)) +>V : Symbol(V, Decl(conditionalTypes2.ts, 144, 10)) +>E : Symbol(E, Decl(conditionalTypes2.ts, 144, 13)) T extends object ? { [Q in keyof T]: C2; } : T; ->T : Symbol(T, Decl(conditionalTypes2.ts, 114, 8)) ->Q : Symbol(Q, Decl(conditionalTypes2.ts, 115, 26)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 114, 8)) ->C2 : Symbol(C2, Decl(conditionalTypes2.ts, 112, 82)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 114, 8)) ->Q : Symbol(Q, Decl(conditionalTypes2.ts, 115, 26)) ->V : Symbol(V, Decl(conditionalTypes2.ts, 114, 10)) ->E : Symbol(E, Decl(conditionalTypes2.ts, 114, 13)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 114, 8)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 144, 8)) +>Q : Symbol(Q, Decl(conditionalTypes2.ts, 145, 26)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 144, 8)) +>C2 : Symbol(C2, Decl(conditionalTypes2.ts, 142, 82)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 144, 8)) +>Q : Symbol(Q, Decl(conditionalTypes2.ts, 145, 26)) +>V : Symbol(V, Decl(conditionalTypes2.ts, 144, 10)) +>E : Symbol(E, Decl(conditionalTypes2.ts, 144, 13)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 144, 8)) // Repro from #28654 type MaybeTrue = true extends T["b"] ? "yes" : "no"; ->MaybeTrue : Symbol(MaybeTrue, Decl(conditionalTypes2.ts, 115, 63)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 119, 15)) ->b : Symbol(b, Decl(conditionalTypes2.ts, 119, 26)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 119, 15)) +>MaybeTrue : Symbol(MaybeTrue, Decl(conditionalTypes2.ts, 145, 63)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 149, 15)) +>b : Symbol(b, Decl(conditionalTypes2.ts, 149, 26)) +>T : Symbol(T, Decl(conditionalTypes2.ts, 149, 15)) type T0 = MaybeTrue<{ b: never }> // "no" ->T0 : Symbol(T0, Decl(conditionalTypes2.ts, 119, 78)) ->MaybeTrue : Symbol(MaybeTrue, Decl(conditionalTypes2.ts, 115, 63)) ->b : Symbol(b, Decl(conditionalTypes2.ts, 121, 21)) +>T0 : Symbol(T0, Decl(conditionalTypes2.ts, 149, 78)) +>MaybeTrue : Symbol(MaybeTrue, Decl(conditionalTypes2.ts, 145, 63)) +>b : Symbol(b, Decl(conditionalTypes2.ts, 151, 21)) type T1 = MaybeTrue<{ b: false }>; // "no" ->T1 : Symbol(T1, Decl(conditionalTypes2.ts, 121, 33)) ->MaybeTrue : Symbol(MaybeTrue, Decl(conditionalTypes2.ts, 115, 63)) ->b : Symbol(b, Decl(conditionalTypes2.ts, 122, 21)) +>T1 : Symbol(T1, Decl(conditionalTypes2.ts, 151, 33)) +>MaybeTrue : Symbol(MaybeTrue, Decl(conditionalTypes2.ts, 145, 63)) +>b : Symbol(b, Decl(conditionalTypes2.ts, 152, 21)) type T2 = MaybeTrue<{ b: true }>; // "yes" ->T2 : Symbol(T2, Decl(conditionalTypes2.ts, 122, 34)) ->MaybeTrue : Symbol(MaybeTrue, Decl(conditionalTypes2.ts, 115, 63)) ->b : Symbol(b, Decl(conditionalTypes2.ts, 123, 21)) +>T2 : Symbol(T2, Decl(conditionalTypes2.ts, 152, 34)) +>MaybeTrue : Symbol(MaybeTrue, Decl(conditionalTypes2.ts, 145, 63)) +>b : Symbol(b, Decl(conditionalTypes2.ts, 153, 21)) type T3 = MaybeTrue<{ b: boolean }>; // "yes" ->T3 : Symbol(T3, Decl(conditionalTypes2.ts, 123, 33)) ->MaybeTrue : Symbol(MaybeTrue, Decl(conditionalTypes2.ts, 115, 63)) ->b : Symbol(b, Decl(conditionalTypes2.ts, 124, 21)) +>T3 : Symbol(T3, Decl(conditionalTypes2.ts, 153, 33)) +>MaybeTrue : Symbol(MaybeTrue, Decl(conditionalTypes2.ts, 145, 63)) +>b : Symbol(b, Decl(conditionalTypes2.ts, 154, 21)) // Repro from #28824 type Union = 'a' | 'b'; ->Union : Symbol(Union, Decl(conditionalTypes2.ts, 124, 36)) +>Union : Symbol(Union, Decl(conditionalTypes2.ts, 154, 36)) type Product = { f1: A, f2: B}; ->Product : Symbol(Product, Decl(conditionalTypes2.ts, 128, 23)) ->A : Symbol(A, Decl(conditionalTypes2.ts, 129, 13)) ->Union : Symbol(Union, Decl(conditionalTypes2.ts, 124, 36)) ->B : Symbol(B, Decl(conditionalTypes2.ts, 129, 29)) ->f1 : Symbol(f1, Decl(conditionalTypes2.ts, 129, 36)) ->A : Symbol(A, Decl(conditionalTypes2.ts, 129, 13)) ->f2 : Symbol(f2, Decl(conditionalTypes2.ts, 129, 43)) ->B : Symbol(B, Decl(conditionalTypes2.ts, 129, 29)) +>Product : Symbol(Product, Decl(conditionalTypes2.ts, 158, 23)) +>A : Symbol(A, Decl(conditionalTypes2.ts, 159, 13)) +>Union : Symbol(Union, Decl(conditionalTypes2.ts, 154, 36)) +>B : Symbol(B, Decl(conditionalTypes2.ts, 159, 29)) +>f1 : Symbol(f1, Decl(conditionalTypes2.ts, 159, 36)) +>A : Symbol(A, Decl(conditionalTypes2.ts, 159, 13)) +>f2 : Symbol(f2, Decl(conditionalTypes2.ts, 159, 43)) +>B : Symbol(B, Decl(conditionalTypes2.ts, 159, 29)) type ProductUnion = Product<'a', 0> | Product<'b', 1>; ->ProductUnion : Symbol(ProductUnion, Decl(conditionalTypes2.ts, 129, 51)) ->Product : Symbol(Product, Decl(conditionalTypes2.ts, 128, 23)) ->Product : Symbol(Product, Decl(conditionalTypes2.ts, 128, 23)) +>ProductUnion : Symbol(ProductUnion, Decl(conditionalTypes2.ts, 159, 51)) +>Product : Symbol(Product, Decl(conditionalTypes2.ts, 158, 23)) +>Product : Symbol(Product, Decl(conditionalTypes2.ts, 158, 23)) // {a: "b"; b: "a"} type UnionComplement = { ->UnionComplement : Symbol(UnionComplement, Decl(conditionalTypes2.ts, 130, 54)) +>UnionComplement : Symbol(UnionComplement, Decl(conditionalTypes2.ts, 160, 54)) [K in Union]: Exclude ->K : Symbol(K, Decl(conditionalTypes2.ts, 134, 3)) ->Union : Symbol(Union, Decl(conditionalTypes2.ts, 124, 36)) +>K : Symbol(K, Decl(conditionalTypes2.ts, 164, 3)) +>Union : Symbol(Union, Decl(conditionalTypes2.ts, 154, 36)) >Exclude : Symbol(Exclude, Decl(lib.es5.d.ts, --, --)) ->Union : Symbol(Union, Decl(conditionalTypes2.ts, 124, 36)) ->K : Symbol(K, Decl(conditionalTypes2.ts, 134, 3)) +>Union : Symbol(Union, Decl(conditionalTypes2.ts, 154, 36)) +>K : Symbol(K, Decl(conditionalTypes2.ts, 164, 3)) }; type UCA = UnionComplement['a']; ->UCA : Symbol(UCA, Decl(conditionalTypes2.ts, 135, 2)) ->UnionComplement : Symbol(UnionComplement, Decl(conditionalTypes2.ts, 130, 54)) +>UCA : Symbol(UCA, Decl(conditionalTypes2.ts, 165, 2)) +>UnionComplement : Symbol(UnionComplement, Decl(conditionalTypes2.ts, 160, 54)) type UCB = UnionComplement['b']; ->UCB : Symbol(UCB, Decl(conditionalTypes2.ts, 136, 32)) ->UnionComplement : Symbol(UnionComplement, Decl(conditionalTypes2.ts, 130, 54)) +>UCB : Symbol(UCB, Decl(conditionalTypes2.ts, 166, 32)) +>UnionComplement : Symbol(UnionComplement, Decl(conditionalTypes2.ts, 160, 54)) // {a: "a"; b: "b"} type UnionComplementComplement = { ->UnionComplementComplement : Symbol(UnionComplementComplement, Decl(conditionalTypes2.ts, 137, 32)) +>UnionComplementComplement : Symbol(UnionComplementComplement, Decl(conditionalTypes2.ts, 167, 32)) [K in Union]: Exclude> ->K : Symbol(K, Decl(conditionalTypes2.ts, 141, 3)) ->Union : Symbol(Union, Decl(conditionalTypes2.ts, 124, 36)) +>K : Symbol(K, Decl(conditionalTypes2.ts, 171, 3)) +>Union : Symbol(Union, Decl(conditionalTypes2.ts, 154, 36)) >Exclude : Symbol(Exclude, Decl(lib.es5.d.ts, --, --)) ->Union : Symbol(Union, Decl(conditionalTypes2.ts, 124, 36)) +>Union : Symbol(Union, Decl(conditionalTypes2.ts, 154, 36)) >Exclude : Symbol(Exclude, Decl(lib.es5.d.ts, --, --)) ->Union : Symbol(Union, Decl(conditionalTypes2.ts, 124, 36)) ->K : Symbol(K, Decl(conditionalTypes2.ts, 141, 3)) +>Union : Symbol(Union, Decl(conditionalTypes2.ts, 154, 36)) +>K : Symbol(K, Decl(conditionalTypes2.ts, 171, 3)) }; type UCCA = UnionComplementComplement['a']; ->UCCA : Symbol(UCCA, Decl(conditionalTypes2.ts, 142, 2)) ->UnionComplementComplement : Symbol(UnionComplementComplement, Decl(conditionalTypes2.ts, 137, 32)) +>UCCA : Symbol(UCCA, Decl(conditionalTypes2.ts, 172, 2)) +>UnionComplementComplement : Symbol(UnionComplementComplement, Decl(conditionalTypes2.ts, 167, 32)) type UCCB = UnionComplementComplement['b']; ->UCCB : Symbol(UCCB, Decl(conditionalTypes2.ts, 143, 43)) ->UnionComplementComplement : Symbol(UnionComplementComplement, Decl(conditionalTypes2.ts, 137, 32)) +>UCCB : Symbol(UCCB, Decl(conditionalTypes2.ts, 173, 43)) +>UnionComplementComplement : Symbol(UnionComplementComplement, Decl(conditionalTypes2.ts, 167, 32)) // {a: Product<'b', 1>; b: Product<'a', 0>} type ProductComplement = { ->ProductComplement : Symbol(ProductComplement, Decl(conditionalTypes2.ts, 144, 43)) +>ProductComplement : Symbol(ProductComplement, Decl(conditionalTypes2.ts, 174, 43)) [K in Union]: Exclude ->K : Symbol(K, Decl(conditionalTypes2.ts, 148, 3)) ->Union : Symbol(Union, Decl(conditionalTypes2.ts, 124, 36)) +>K : Symbol(K, Decl(conditionalTypes2.ts, 178, 3)) +>Union : Symbol(Union, Decl(conditionalTypes2.ts, 154, 36)) >Exclude : Symbol(Exclude, Decl(lib.es5.d.ts, --, --)) ->ProductUnion : Symbol(ProductUnion, Decl(conditionalTypes2.ts, 129, 51)) ->f1 : Symbol(f1, Decl(conditionalTypes2.ts, 148, 39)) ->K : Symbol(K, Decl(conditionalTypes2.ts, 148, 3)) +>ProductUnion : Symbol(ProductUnion, Decl(conditionalTypes2.ts, 159, 51)) +>f1 : Symbol(f1, Decl(conditionalTypes2.ts, 178, 39)) +>K : Symbol(K, Decl(conditionalTypes2.ts, 178, 3)) }; type PCA = ProductComplement['a']; ->PCA : Symbol(PCA, Decl(conditionalTypes2.ts, 149, 2)) ->ProductComplement : Symbol(ProductComplement, Decl(conditionalTypes2.ts, 144, 43)) +>PCA : Symbol(PCA, Decl(conditionalTypes2.ts, 179, 2)) +>ProductComplement : Symbol(ProductComplement, Decl(conditionalTypes2.ts, 174, 43)) type PCB = ProductComplement['b']; ->PCB : Symbol(PCB, Decl(conditionalTypes2.ts, 150, 34)) ->ProductComplement : Symbol(ProductComplement, Decl(conditionalTypes2.ts, 144, 43)) +>PCB : Symbol(PCB, Decl(conditionalTypes2.ts, 180, 34)) +>ProductComplement : Symbol(ProductComplement, Decl(conditionalTypes2.ts, 174, 43)) // {a: Product<'a', 0>; b: Product<'b', 1>} type ProductComplementComplement = { ->ProductComplementComplement : Symbol(ProductComplementComplement, Decl(conditionalTypes2.ts, 151, 34)) +>ProductComplementComplement : Symbol(ProductComplementComplement, Decl(conditionalTypes2.ts, 181, 34)) [K in Union]: Exclude> ->K : Symbol(K, Decl(conditionalTypes2.ts, 155, 3)) ->Union : Symbol(Union, Decl(conditionalTypes2.ts, 124, 36)) +>K : Symbol(K, Decl(conditionalTypes2.ts, 185, 3)) +>Union : Symbol(Union, Decl(conditionalTypes2.ts, 154, 36)) >Exclude : Symbol(Exclude, Decl(lib.es5.d.ts, --, --)) ->ProductUnion : Symbol(ProductUnion, Decl(conditionalTypes2.ts, 129, 51)) +>ProductUnion : Symbol(ProductUnion, Decl(conditionalTypes2.ts, 159, 51)) >Exclude : Symbol(Exclude, Decl(lib.es5.d.ts, --, --)) ->ProductUnion : Symbol(ProductUnion, Decl(conditionalTypes2.ts, 129, 51)) ->f1 : Symbol(f1, Decl(conditionalTypes2.ts, 155, 61)) ->K : Symbol(K, Decl(conditionalTypes2.ts, 155, 3)) +>ProductUnion : Symbol(ProductUnion, Decl(conditionalTypes2.ts, 159, 51)) +>f1 : Symbol(f1, Decl(conditionalTypes2.ts, 185, 61)) +>K : Symbol(K, Decl(conditionalTypes2.ts, 185, 3)) }; type PCCA = ProductComplementComplement['a']; ->PCCA : Symbol(PCCA, Decl(conditionalTypes2.ts, 156, 2)) ->ProductComplementComplement : Symbol(ProductComplementComplement, Decl(conditionalTypes2.ts, 151, 34)) +>PCCA : Symbol(PCCA, Decl(conditionalTypes2.ts, 186, 2)) +>ProductComplementComplement : Symbol(ProductComplementComplement, Decl(conditionalTypes2.ts, 181, 34)) type PCCB = ProductComplementComplement['b']; ->PCCB : Symbol(PCCB, Decl(conditionalTypes2.ts, 157, 45)) ->ProductComplementComplement : Symbol(ProductComplementComplement, Decl(conditionalTypes2.ts, 151, 34)) - -// Repros from #27118 - -type MyElement = [A] extends [[infer E]] ? E : never; ->MyElement : Symbol(MyElement, Decl(conditionalTypes2.ts, 158, 45)) ->A : Symbol(A, Decl(conditionalTypes2.ts, 162, 15)) ->A : Symbol(A, Decl(conditionalTypes2.ts, 162, 15)) ->E : Symbol(E, Decl(conditionalTypes2.ts, 162, 39)) ->E : Symbol(E, Decl(conditionalTypes2.ts, 162, 39)) - -function oops(arg: MyElement): MyElement { ->oops : Symbol(oops, Decl(conditionalTypes2.ts, 162, 56)) ->A : Symbol(A, Decl(conditionalTypes2.ts, 163, 14)) ->B : Symbol(B, Decl(conditionalTypes2.ts, 163, 16)) ->A : Symbol(A, Decl(conditionalTypes2.ts, 163, 14)) ->arg : Symbol(arg, Decl(conditionalTypes2.ts, 163, 30)) ->MyElement : Symbol(MyElement, Decl(conditionalTypes2.ts, 158, 45)) ->A : Symbol(A, Decl(conditionalTypes2.ts, 163, 14)) ->MyElement : Symbol(MyElement, Decl(conditionalTypes2.ts, 158, 45)) ->B : Symbol(B, Decl(conditionalTypes2.ts, 163, 16)) - - return arg; // Unsound, should be error ->arg : Symbol(arg, Decl(conditionalTypes2.ts, 163, 30)) -} - -type MyAcceptor = [A] extends [[infer E]] ? (arg: E) => void : never; ->MyAcceptor : Symbol(MyAcceptor, Decl(conditionalTypes2.ts, 165, 1)) ->A : Symbol(A, Decl(conditionalTypes2.ts, 167, 16)) ->A : Symbol(A, Decl(conditionalTypes2.ts, 167, 16)) ->E : Symbol(E, Decl(conditionalTypes2.ts, 167, 40)) ->arg : Symbol(arg, Decl(conditionalTypes2.ts, 167, 48)) ->E : Symbol(E, Decl(conditionalTypes2.ts, 167, 40)) - -function oops2(arg: MyAcceptor): MyAcceptor { ->oops2 : Symbol(oops2, Decl(conditionalTypes2.ts, 167, 72)) ->A : Symbol(A, Decl(conditionalTypes2.ts, 168, 15)) ->B : Symbol(B, Decl(conditionalTypes2.ts, 168, 17)) ->A : Symbol(A, Decl(conditionalTypes2.ts, 168, 15)) ->arg : Symbol(arg, Decl(conditionalTypes2.ts, 168, 31)) ->MyAcceptor : Symbol(MyAcceptor, Decl(conditionalTypes2.ts, 165, 1)) ->B : Symbol(B, Decl(conditionalTypes2.ts, 168, 17)) ->MyAcceptor : Symbol(MyAcceptor, Decl(conditionalTypes2.ts, 165, 1)) ->A : Symbol(A, Decl(conditionalTypes2.ts, 168, 15)) - - return arg; // Unsound, should be error ->arg : Symbol(arg, Decl(conditionalTypes2.ts, 168, 31)) -} - -type Dist = T extends number ? number : string; ->Dist : Symbol(Dist, Decl(conditionalTypes2.ts, 170, 1)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 172, 10)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 172, 10)) - -type Aux = A["a"] extends number ? number : string; ->Aux : Symbol(Aux, Decl(conditionalTypes2.ts, 172, 50)) ->A : Symbol(A, Decl(conditionalTypes2.ts, 173, 9)) ->a : Symbol(a, Decl(conditionalTypes2.ts, 173, 20)) ->A : Symbol(A, Decl(conditionalTypes2.ts, 173, 9)) - -type Nondist = Aux<{a: T}>; ->Nondist : Symbol(Nondist, Decl(conditionalTypes2.ts, 173, 77)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 174, 13)) ->Aux : Symbol(Aux, Decl(conditionalTypes2.ts, 172, 50)) ->a : Symbol(a, Decl(conditionalTypes2.ts, 174, 23)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 174, 13)) - -function oops3(arg: Dist): Nondist { ->oops3 : Symbol(oops3, Decl(conditionalTypes2.ts, 174, 30)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 175, 15)) ->arg : Symbol(arg, Decl(conditionalTypes2.ts, 175, 18)) ->Dist : Symbol(Dist, Decl(conditionalTypes2.ts, 170, 1)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 175, 15)) ->Nondist : Symbol(Nondist, Decl(conditionalTypes2.ts, 173, 77)) ->T : Symbol(T, Decl(conditionalTypes2.ts, 175, 15)) - - return arg; // Unsound, should be error ->arg : Symbol(arg, Decl(conditionalTypes2.ts, 175, 18)) -} +>PCCB : Symbol(PCCB, Decl(conditionalTypes2.ts, 187, 45)) +>ProductComplementComplement : Symbol(ProductComplementComplement, Decl(conditionalTypes2.ts, 181, 34)) diff --git a/tests/baselines/reference/conditionalTypes2.types b/tests/baselines/reference/conditionalTypes2.types index 3cffe6ab48e..aac6ba47475 100644 --- a/tests/baselines/reference/conditionalTypes2.types +++ b/tests/baselines/reference/conditionalTypes2.types @@ -1,6 +1,4 @@ === tests/cases/conformance/types/conditional/conditionalTypes2.ts === -// #27118: Conditional types are now invariant in the check type. - interface Covariant { foo: T extends string ? T : number; >foo : T extends string ? T : number @@ -21,7 +19,7 @@ function f1(a: Covariant, b: Covariant) { >a : Covariant >b : Covariant - a = b; // Error + a = b; >a = b : Covariant >a : Covariant >b : Covariant @@ -42,7 +40,7 @@ function f2(a: Contravariant, b: Contravariant) { >a : Contravariant >b : Contravariant - b = a; // Error + b = a; >b = a : Contravariant >b : Contravariant >a : Contravariant @@ -209,6 +207,71 @@ function f21(x: Extract, Bar>, y: Extract, z: E >z : Extract2 } +// Repros from #22860 + +class Opt { +>Opt : Opt + + toVector(): Vector { +>toVector : () => Vector + + return undefined; +>undefined : any +>undefined : undefined + } +} + +interface Seq { + tail(): Opt>; +>tail : () => Opt> +} + +class Vector implements Seq { +>Vector : Vector + + tail(): Opt> { +>tail : () => Opt> + + return undefined; +>undefined : any +>undefined : undefined + } + partition2(predicate:(v:T)=>v is U): [Vector,Vector>]; +>partition2 : { (predicate: (v: T) => v is U): [Vector, Vector>]; (predicate: (x: T) => boolean): [Vector, Vector]; } +>predicate : (v: T) => v is U +>v : T + + partition2(predicate:(x:T)=>boolean): [Vector,Vector]; +>partition2 : { (predicate: (v: T) => v is U): [Vector, Vector>]; (predicate: (x: T) => boolean): [Vector, Vector]; } +>predicate : (x: T) => boolean +>x : T + + partition2(predicate:(v:T)=>boolean): [Vector,Vector] { +>partition2 : { (predicate: (v: T) => v is U): [Vector, Vector>]; (predicate: (x: T) => boolean): [Vector, Vector]; } +>predicate : (v: T) => boolean +>v : T + + return undefined; +>undefined : any +>undefined : undefined + } +} + +interface A1 { + bat: B1>; +>bat : B1> +} + +interface B1 extends A1 { + bat: B1>; +>bat : B1> + + boom: T extends any ? true : true +>boom : T extends any ? true : true +>true : true +>true : true +} + // Repro from #22899 declare function toString1(value: object | Function): string ; @@ -368,47 +431,3 @@ type PCCA = ProductComplementComplement['a']; type PCCB = ProductComplementComplement['b']; >PCCB : Product<"b", 1> -// Repros from #27118 - -type MyElement = [A] extends [[infer E]] ? E : never; ->MyElement : MyElement - -function oops(arg: MyElement): MyElement { ->oops : (arg: MyElement) => MyElement ->arg : MyElement - - return arg; // Unsound, should be error ->arg : MyElement -} - -type MyAcceptor = [A] extends [[infer E]] ? (arg: E) => void : never; ->MyAcceptor : MyAcceptor ->arg : E - -function oops2(arg: MyAcceptor): MyAcceptor { ->oops2 : (arg: MyAcceptor) => MyAcceptor ->arg : MyAcceptor - - return arg; // Unsound, should be error ->arg : MyAcceptor -} - -type Dist = T extends number ? number : string; ->Dist : Dist - -type Aux = A["a"] extends number ? number : string; ->Aux : Aux ->a : unknown - -type Nondist = Aux<{a: T}>; ->Nondist : Aux<{ a: T; }> ->a : T - -function oops3(arg: Dist): Nondist { ->oops3 : (arg: Dist) => Aux<{ a: T; }> ->arg : Dist - - return arg; // Unsound, should be error ->arg : Dist -} - diff --git a/tests/cases/conformance/types/conditional/conditionalTypes2.ts b/tests/cases/conformance/types/conditional/conditionalTypes2.ts index 5d73c58fe7f..4b65b5ddeb2 100644 --- a/tests/cases/conformance/types/conditional/conditionalTypes2.ts +++ b/tests/cases/conformance/types/conditional/conditionalTypes2.ts @@ -1,8 +1,6 @@ // @strict: true // @declaration: true -// #27118: Conditional types are now invariant in the check type. - interface Covariant { foo: T extends string ? T : number; } @@ -16,13 +14,13 @@ interface Invariant { } function f1(a: Covariant, b: Covariant) { - a = b; // Error + a = b; b = a; // Error } function f2(a: Contravariant, b: Contravariant) { a = b; // Error - b = a; // Error + b = a; } function f3(a: Invariant, b: Invariant) { @@ -80,6 +78,38 @@ function f21(x: Extract, Bar>, y: Extract, z: E fooBat(z); // Error } +// Repros from #22860 + +class Opt { + toVector(): Vector { + return undefined; + } +} + +interface Seq { + tail(): Opt>; +} + +class Vector implements Seq { + tail(): Opt> { + return undefined; + } + partition2(predicate:(v:T)=>v is U): [Vector,Vector>]; + partition2(predicate:(x:T)=>boolean): [Vector,Vector]; + partition2(predicate:(v:T)=>boolean): [Vector,Vector] { + return undefined; + } +} + +interface A1 { + bat: B1>; +} + +interface B1 extends A1 { + bat: B1>; + boom: T extends any ? true : true +} + // Repro from #22899 declare function toString1(value: object | Function): string ; @@ -160,22 +190,3 @@ type ProductComplementComplement = { }; type PCCA = ProductComplementComplement['a']; type PCCB = ProductComplementComplement['b']; - -// Repros from #27118 - -type MyElement = [A] extends [[infer E]] ? E : never; -function oops(arg: MyElement): MyElement { - return arg; // Unsound, should be error -} - -type MyAcceptor = [A] extends [[infer E]] ? (arg: E) => void : never; -function oops2(arg: MyAcceptor): MyAcceptor { - return arg; // Unsound, should be error -} - -type Dist = T extends number ? number : string; -type Aux = A["a"] extends number ? number : string; -type Nondist = Aux<{a: T}>; -function oops3(arg: Dist): Nondist { - return arg; // Unsound, should be error -} From f77b43ca090b1c402859e79a31d54238a478c143 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Wed, 27 Feb 2019 12:42:30 -0800 Subject: [PATCH 124/149] Update baselines --- .../reference/conditionalTypes2.errors.txt | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/tests/baselines/reference/conditionalTypes2.errors.txt b/tests/baselines/reference/conditionalTypes2.errors.txt index a1a23b6da18..6cf81cf5730 100644 --- a/tests/baselines/reference/conditionalTypes2.errors.txt +++ b/tests/baselines/reference/conditionalTypes2.errors.txt @@ -8,6 +8,13 @@ tests/cases/conformance/types/conditional/conditionalTypes2.ts(24,5): error TS23 Type 'keyof B' is not assignable to type 'keyof A'. Type 'string | number | symbol' is not assignable to type 'keyof A'. Type 'string' is not assignable to type 'keyof A'. + Type 'string' is not assignable to type 'number | "toString" | "charAt" | "charCodeAt" | "concat" | "indexOf" | "lastIndexOf" | "localeCompare" | "match" | "replace" | "search" | "slice" | "split" | "substring" | "toLowerCase" | "toLocaleLowerCase" | "toUpperCase" | "toLocaleUpperCase" | "trim" | "length" | "substr" | "valueOf"'. + Type 'keyof B' is not assignable to type 'number | "toString" | "charAt" | "charCodeAt" | "concat" | "indexOf" | "lastIndexOf" | "localeCompare" | "match" | "replace" | "search" | "slice" | "split" | "substring" | "toLowerCase" | "toLocaleLowerCase" | "toUpperCase" | "toLocaleUpperCase" | "trim" | "length" | "substr" | "valueOf"'. + Type 'string | number | symbol' is not assignable to type 'number | "toString" | "charAt" | "charCodeAt" | "concat" | "indexOf" | "lastIndexOf" | "localeCompare" | "match" | "replace" | "search" | "slice" | "split" | "substring" | "toLowerCase" | "toLocaleLowerCase" | "toUpperCase" | "toLocaleUpperCase" | "trim" | "length" | "substr" | "valueOf"'. + Type 'string' is not assignable to type 'number | "toString" | "charAt" | "charCodeAt" | "concat" | "indexOf" | "lastIndexOf" | "localeCompare" | "match" | "replace" | "search" | "slice" | "split" | "substring" | "toLowerCase" | "toLocaleLowerCase" | "toUpperCase" | "toLocaleUpperCase" | "trim" | "length" | "substr" | "valueOf"'. + Type 'keyof B' is not assignable to type '"valueOf"'. + Type 'string | number | symbol' is not assignable to type '"valueOf"'. + Type 'string' is not assignable to type '"valueOf"'. tests/cases/conformance/types/conditional/conditionalTypes2.ts(25,5): error TS2322: Type 'Invariant' is not assignable to type 'Invariant'. Types of property 'foo' are incompatible. Type 'A extends string ? keyof A : A' is not assignable to type 'B extends string ? keyof B : B'. @@ -61,6 +68,13 @@ tests/cases/conformance/types/conditional/conditionalTypes2.ts(75,12): error TS2 !!! error TS2322: Type 'keyof B' is not assignable to type 'keyof A'. !!! error TS2322: Type 'string | number | symbol' is not assignable to type 'keyof A'. !!! error TS2322: Type 'string' is not assignable to type 'keyof A'. +!!! error TS2322: Type 'string' is not assignable to type 'number | "toString" | "charAt" | "charCodeAt" | "concat" | "indexOf" | "lastIndexOf" | "localeCompare" | "match" | "replace" | "search" | "slice" | "split" | "substring" | "toLowerCase" | "toLocaleLowerCase" | "toUpperCase" | "toLocaleUpperCase" | "trim" | "length" | "substr" | "valueOf"'. +!!! error TS2322: Type 'keyof B' is not assignable to type 'number | "toString" | "charAt" | "charCodeAt" | "concat" | "indexOf" | "lastIndexOf" | "localeCompare" | "match" | "replace" | "search" | "slice" | "split" | "substring" | "toLowerCase" | "toLocaleLowerCase" | "toUpperCase" | "toLocaleUpperCase" | "trim" | "length" | "substr" | "valueOf"'. +!!! error TS2322: Type 'string | number | symbol' is not assignable to type 'number | "toString" | "charAt" | "charCodeAt" | "concat" | "indexOf" | "lastIndexOf" | "localeCompare" | "match" | "replace" | "search" | "slice" | "split" | "substring" | "toLowerCase" | "toLocaleLowerCase" | "toUpperCase" | "toLocaleUpperCase" | "trim" | "length" | "substr" | "valueOf"'. +!!! error TS2322: Type 'string' is not assignable to type 'number | "toString" | "charAt" | "charCodeAt" | "concat" | "indexOf" | "lastIndexOf" | "localeCompare" | "match" | "replace" | "search" | "slice" | "split" | "substring" | "toLowerCase" | "toLocaleLowerCase" | "toUpperCase" | "toLocaleUpperCase" | "trim" | "length" | "substr" | "valueOf"'. +!!! error TS2322: Type 'keyof B' is not assignable to type '"valueOf"'. +!!! error TS2322: Type 'string | number | symbol' is not assignable to type '"valueOf"'. +!!! error TS2322: Type 'string' is not assignable to type '"valueOf"'. b = a; // Error ~ !!! error TS2322: Type 'Invariant' is not assignable to type 'Invariant'. From 03377f70b776d5e1279a70d2e75b45a45483ba0d Mon Sep 17 00:00:00 2001 From: Sheetal Nandi Date: Wed, 27 Feb 2019 14:07:15 -0800 Subject: [PATCH 125/149] Apply changes in reverse order even in new API to match behaviour with internal api --- src/server/session.ts | 2 +- src/testRunner/unittests/tsserver/applyChangesToOpenFiles.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/server/session.ts b/src/server/session.ts index 42946002bc4..af84ffff48a 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -2107,7 +2107,7 @@ namespace ts.server { })), request.arguments.changedFiles && mapIterator(arrayIterator(request.arguments.changedFiles), file => ({ fileName: file.fileName, - changes: mapDefinedIterator(arrayIterator(file.textChanges), change => { + changes: mapDefinedIterator(arrayReverseIterator(file.textChanges), change => { const scriptInfo = Debug.assertDefined(this.projectService.getScriptInfo(file.fileName)); const start = scriptInfo.lineOffsetToPosition(change.start.line, change.start.offset); const end = scriptInfo.lineOffsetToPosition(change.end.line, change.end.offset); diff --git a/src/testRunner/unittests/tsserver/applyChangesToOpenFiles.ts b/src/testRunner/unittests/tsserver/applyChangesToOpenFiles.ts index 3c0da365bb5..68c3839e789 100644 --- a/src/testRunner/unittests/tsserver/applyChangesToOpenFiles.ts +++ b/src/testRunner/unittests/tsserver/applyChangesToOpenFiles.ts @@ -127,12 +127,12 @@ ${file.content}`; { start: { line: 1, offset: 1 }, end: { line: 1, offset: 1 }, - newText: "let zz = 10;", + newText: "let zzz = 10;", }, { start: { line: 1, offset: 1 }, end: { line: 1, offset: 1 }, - newText: "let zzz = 10;", + newText: "let zz = 10;", } ] } From 13c08ab32b0aba3d2580671c9436f7a3d6dd6956 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Wed, 27 Feb 2019 14:12:30 -0800 Subject: [PATCH 126/149] Use identity with the permissive instantation to detect nongenric instances and disable variance probing on nongeneric instances (#29981) * Use identity with the restrictive instantation to detect nongenric instances and disable variance probing on nongeneric instances * Generalize to also include interfaces, add test case, still perform argument comparisons for postive comparisons if possible * Actually accept baselines, lol * Reduce deep nesting limit just a bit so yargs still builds * Handle circular identities in isNonGeneric * Use a simple traversal of the types rather than the restrictive instantiation * Cache the bits using an existing field to further reduce any time nongeneric check takes * Revert to using an existing mapper, use permissive > restrictive * Revert constant change * And revert the comment, too --- src/compiler/checker.ts | 16 +- ...eckInfiniteExpansionTermination.errors.txt | 32 ---- ...nvariantGenericErrorElaboration.errors.txt | 52 ------ .../invariantGenericErrorElaboration.types | 4 +- .../mappedTypeRelationships.errors.txt | 4 - ...alInstantiationsRelatedInBothDirections.js | 18 ++ ...tantiationsRelatedInBothDirections.symbols | 43 +++++ ...nstantiationsRelatedInBothDirections.types | 33 ++++ .../recursiveTypeComparison.errors.txt | 27 --- .../baselines/reference/specedNoStackBlown.js | 47 ++++++ .../reference/specedNoStackBlown.symbols | 158 ++++++++++++++++++ .../reference/specedNoStackBlown.types | 64 +++++++ .../strictFunctionTypesErrors.errors.txt | 16 +- ...derIndexSignatureRelationsAlign.errors.txt | 82 --------- ...eroOrderIndexSignatureRelationsAlign.types | 2 +- ...erIndexSignatureRelationsAlign2.errors.txt | 79 --------- ...alInstantiationsRelatedInBothDirections.ts | 12 ++ tests/cases/compiler/specedNoStackBlown.ts | 35 ++++ 18 files changed, 430 insertions(+), 294 deletions(-) delete mode 100644 tests/baselines/reference/checkInfiniteExpansionTermination.errors.txt delete mode 100644 tests/baselines/reference/invariantGenericErrorElaboration.errors.txt create mode 100644 tests/baselines/reference/nongenericPartialInstantiationsRelatedInBothDirections.js create mode 100644 tests/baselines/reference/nongenericPartialInstantiationsRelatedInBothDirections.symbols create mode 100644 tests/baselines/reference/nongenericPartialInstantiationsRelatedInBothDirections.types delete mode 100644 tests/baselines/reference/recursiveTypeComparison.errors.txt create mode 100644 tests/baselines/reference/specedNoStackBlown.js create mode 100644 tests/baselines/reference/specedNoStackBlown.symbols create mode 100644 tests/baselines/reference/specedNoStackBlown.types delete mode 100644 tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign.errors.txt delete mode 100644 tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.errors.txt create mode 100644 tests/cases/compiler/nongenericPartialInstantiationsRelatedInBothDirections.ts create mode 100644 tests/cases/compiler/specedNoStackBlown.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 80853ca2eaf..247c789577c 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -12822,12 +12822,22 @@ namespace ts { } return Ternary.False; + function isNonGeneric(type: Type) { + // If we're already in identity relationship checking, we should use `isRelatedTo` + // to catch the `Maybe` from an excessively deep type (which we then assume means + // that the type could possibly contain a generic) + if (relation === identityRelation) { + return isRelatedTo(type, getPermissiveInstantiation(type)) === Ternary.True; + } + return isTypeIdenticalTo(type, getPermissiveInstantiation(type)); + } + function relateVariances(sourceTypeArguments: ReadonlyArray | undefined, targetTypeArguments: ReadonlyArray | undefined, variances: Variance[]) { if (result = typeArgumentsRelatedTo(sourceTypeArguments, targetTypeArguments, variances, reportErrors)) { return result; } - const isCovariantVoid = targetTypeArguments && hasCovariantVoidArgument(targetTypeArguments, variances); - varianceCheckFailed = !isCovariantVoid; + const allowStructuralFallback = (targetTypeArguments && hasCovariantVoidArgument(targetTypeArguments, variances)) || isNonGeneric(source) || isNonGeneric(target); + varianceCheckFailed = !allowStructuralFallback; // The type arguments did not relate appropriately, but it may be because we have no variance // information (in which case typeArgumentsRelatedTo defaulted to covariance for all type // arguments). It might also be the case that the target type has a 'void' type argument for @@ -12835,7 +12845,7 @@ namespace ts { // (in which case any type argument is permitted on the source side). In those cases we proceed // with a structural comparison. Otherwise, we know for certain the instantiations aren't // related and we can return here. - if (variances !== emptyArray && !isCovariantVoid) { + if (variances !== emptyArray && !allowStructuralFallback) { // In some cases generic types that are covariant in regular type checking mode become // invariant in --strictFunctionTypes mode because one or more type parameters are used in // both co- and contravariant positions. In order to make it easier to diagnose *why* such diff --git a/tests/baselines/reference/checkInfiniteExpansionTermination.errors.txt b/tests/baselines/reference/checkInfiniteExpansionTermination.errors.txt deleted file mode 100644 index 014087ff627..00000000000 --- a/tests/baselines/reference/checkInfiniteExpansionTermination.errors.txt +++ /dev/null @@ -1,32 +0,0 @@ -tests/cases/compiler/checkInfiniteExpansionTermination.ts(16,1): error TS2322: Type 'ISubject' is not assignable to type 'IObservable'. - Types of property 'n' are incompatible. - Type 'IObservable' is not assignable to type 'IObservable'. - Type 'Bar[]' is not assignable to type 'Foo[]'. - Property 'x' is missing in type 'Bar' but required in type 'Foo'. - - -==== tests/cases/compiler/checkInfiniteExpansionTermination.ts (1 errors) ==== - // Regression test for #1002 - // Before fix this code would cause infinite loop - - interface IObservable { - n: IObservable; // Needed, must be T[] - } - - // Needed - interface ISubject extends IObservable { } - - interface Foo { x } - interface Bar { y } - - var values: IObservable; - var values2: ISubject; - values = values2; - ~~~~~~ -!!! error TS2322: Type 'ISubject' is not assignable to type 'IObservable'. -!!! error TS2322: Types of property 'n' are incompatible. -!!! error TS2322: Type 'IObservable' is not assignable to type 'IObservable'. -!!! error TS2322: Type 'Bar[]' is not assignable to type 'Foo[]'. -!!! error TS2322: Property 'x' is missing in type 'Bar' but required in type 'Foo'. -!!! related TS2728 tests/cases/compiler/checkInfiniteExpansionTermination.ts:11:17: 'x' is declared here. - \ No newline at end of file diff --git a/tests/baselines/reference/invariantGenericErrorElaboration.errors.txt b/tests/baselines/reference/invariantGenericErrorElaboration.errors.txt deleted file mode 100644 index 0bd79bcf11d..00000000000 --- a/tests/baselines/reference/invariantGenericErrorElaboration.errors.txt +++ /dev/null @@ -1,52 +0,0 @@ -tests/cases/compiler/invariantGenericErrorElaboration.ts(3,7): error TS2322: Type 'Num' is not assignable to type 'Runtype'. - Types of property 'constraint' are incompatible. - Type 'Constraint' is not assignable to type 'Constraint>'. - Types of property 'constraint' are incompatible. - Type 'Constraint>' is not assignable to type 'Constraint>>'. - Types of property 'constraint' are incompatible. - Type 'Constraint>>' is not assignable to type 'Constraint>>>'. - Type 'Constraint>>' is not assignable to type 'Constraint>'. - Types of property 'underlying' are incompatible. - Type 'Constraint>' is not assignable to type 'Constraint'. -tests/cases/compiler/invariantGenericErrorElaboration.ts(4,19): error TS2322: Type 'Num' is not assignable to type 'Runtype'. - - -==== tests/cases/compiler/invariantGenericErrorElaboration.ts (2 errors) ==== - // Repro from #19746 - - const wat: Runtype = Num; - ~~~ -!!! error TS2322: Type 'Num' is not assignable to type 'Runtype'. -!!! error TS2322: Types of property 'constraint' are incompatible. -!!! error TS2322: Type 'Constraint' is not assignable to type 'Constraint>'. -!!! error TS2322: Types of property 'constraint' are incompatible. -!!! error TS2322: Type 'Constraint>' is not assignable to type 'Constraint>>'. -!!! error TS2322: Types of property 'constraint' are incompatible. -!!! error TS2322: Type 'Constraint>>' is not assignable to type 'Constraint>>>'. -!!! error TS2322: Type 'Constraint>>' is not assignable to type 'Constraint>'. -!!! error TS2322: Types of property 'underlying' are incompatible. -!!! error TS2322: Type 'Constraint>' is not assignable to type 'Constraint'. -!!! related TS2728 tests/cases/compiler/invariantGenericErrorElaboration.ts:12:3: 'tag' is declared here. - const Foo = Obj({ foo: Num }) - ~~~ -!!! error TS2322: Type 'Num' is not assignable to type 'Runtype'. -!!! related TS6501 tests/cases/compiler/invariantGenericErrorElaboration.ts:17:34: The expected type comes from this index signature. - - interface Runtype { - constraint: Constraint - witness: A - } - - interface Num extends Runtype { - tag: 'number' - } - declare const Num: Num - - interface Obj }> extends Runtype<{[K in keyof O]: O[K]['witness'] }> {} - declare function Obj }>(fields: O): Obj; - - interface Constraint> extends Runtype { - underlying: A, - check: (x: A['witness']) => void, - } - \ No newline at end of file diff --git a/tests/baselines/reference/invariantGenericErrorElaboration.types b/tests/baselines/reference/invariantGenericErrorElaboration.types index 7c4bdd46d03..86aec86face 100644 --- a/tests/baselines/reference/invariantGenericErrorElaboration.types +++ b/tests/baselines/reference/invariantGenericErrorElaboration.types @@ -6,8 +6,8 @@ const wat: Runtype = Num; >Num : Num const Foo = Obj({ foo: Num }) ->Foo : any ->Obj({ foo: Num }) : any +>Foo : Obj<{ foo: Num; }> +>Obj({ foo: Num }) : Obj<{ foo: Num; }> >Obj : ; }>(fields: O) => Obj >{ foo: Num } : { foo: Num; } >foo : Num diff --git a/tests/baselines/reference/mappedTypeRelationships.errors.txt b/tests/baselines/reference/mappedTypeRelationships.errors.txt index 3d637654079..60a06e000c2 100644 --- a/tests/baselines/reference/mappedTypeRelationships.errors.txt +++ b/tests/baselines/reference/mappedTypeRelationships.errors.txt @@ -34,9 +34,7 @@ tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(66,5): error TS2 tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(66,5): error TS2542: Index signature in type 'Readonly' only permits reading. tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(72,5): error TS2322: Type 'Partial' is not assignable to type 'T'. tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(78,5): error TS2322: Type 'Partial' is not assignable to type 'Partial'. - Type 'Thing' is not assignable to type 'T'. tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(88,5): error TS2322: Type 'Readonly' is not assignable to type 'Readonly'. - Type 'Thing' is not assignable to type 'T'. tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(127,5): error TS2322: Type 'Partial' is not assignable to type 'Identity'. tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(143,5): error TS2322: Type '{ [P in keyof T]: T[P]; }' is not assignable to type '{ [P in keyof T]: U[P]; }'. Type 'T[P]' is not assignable to type 'U[P]'. @@ -199,7 +197,6 @@ tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(168,5): error TS y = x; // Error ~ !!! error TS2322: Type 'Partial' is not assignable to type 'Partial'. -!!! error TS2322: Type 'Thing' is not assignable to type 'T'. } function f40(x: T, y: Readonly) { @@ -212,7 +209,6 @@ tests/cases/conformance/types/mapped/mappedTypeRelationships.ts(168,5): error TS y = x; // Error ~ !!! error TS2322: Type 'Readonly' is not assignable to type 'Readonly'. -!!! error TS2322: Type 'Thing' is not assignable to type 'T'. } type Item = { diff --git a/tests/baselines/reference/nongenericPartialInstantiationsRelatedInBothDirections.js b/tests/baselines/reference/nongenericPartialInstantiationsRelatedInBothDirections.js new file mode 100644 index 00000000000..630adb92c43 --- /dev/null +++ b/tests/baselines/reference/nongenericPartialInstantiationsRelatedInBothDirections.js @@ -0,0 +1,18 @@ +//// [nongenericPartialInstantiationsRelatedInBothDirections.ts] +interface Foo { + a: number; + b: number; + bar: string; +} +interface ObjectContaining { + new (sample: Partial): Partial +} +declare let cafoo: ObjectContaining<{ a: number, foo: number }>; +declare let cfoo: ObjectContaining; +cfoo = cafoo; +cafoo = cfoo; + + +//// [nongenericPartialInstantiationsRelatedInBothDirections.js] +cfoo = cafoo; +cafoo = cfoo; diff --git a/tests/baselines/reference/nongenericPartialInstantiationsRelatedInBothDirections.symbols b/tests/baselines/reference/nongenericPartialInstantiationsRelatedInBothDirections.symbols new file mode 100644 index 00000000000..ee61fa0fd88 --- /dev/null +++ b/tests/baselines/reference/nongenericPartialInstantiationsRelatedInBothDirections.symbols @@ -0,0 +1,43 @@ +=== tests/cases/compiler/nongenericPartialInstantiationsRelatedInBothDirections.ts === +interface Foo { +>Foo : Symbol(Foo, Decl(nongenericPartialInstantiationsRelatedInBothDirections.ts, 0, 0)) + + a: number; +>a : Symbol(Foo.a, Decl(nongenericPartialInstantiationsRelatedInBothDirections.ts, 0, 15)) + + b: number; +>b : Symbol(Foo.b, Decl(nongenericPartialInstantiationsRelatedInBothDirections.ts, 1, 14)) + + bar: string; +>bar : Symbol(Foo.bar, Decl(nongenericPartialInstantiationsRelatedInBothDirections.ts, 2, 14)) +} +interface ObjectContaining { +>ObjectContaining : Symbol(ObjectContaining, Decl(nongenericPartialInstantiationsRelatedInBothDirections.ts, 4, 1)) +>T : Symbol(T, Decl(nongenericPartialInstantiationsRelatedInBothDirections.ts, 5, 27)) + + new (sample: Partial): Partial +>sample : Symbol(sample, Decl(nongenericPartialInstantiationsRelatedInBothDirections.ts, 6, 7)) +>Partial : Symbol(Partial, Decl(lib.es5.d.ts, --, --)) +>T : Symbol(T, Decl(nongenericPartialInstantiationsRelatedInBothDirections.ts, 5, 27)) +>Partial : Symbol(Partial, Decl(lib.es5.d.ts, --, --)) +>T : Symbol(T, Decl(nongenericPartialInstantiationsRelatedInBothDirections.ts, 5, 27)) +} +declare let cafoo: ObjectContaining<{ a: number, foo: number }>; +>cafoo : Symbol(cafoo, Decl(nongenericPartialInstantiationsRelatedInBothDirections.ts, 8, 11)) +>ObjectContaining : Symbol(ObjectContaining, Decl(nongenericPartialInstantiationsRelatedInBothDirections.ts, 4, 1)) +>a : Symbol(a, Decl(nongenericPartialInstantiationsRelatedInBothDirections.ts, 8, 37)) +>foo : Symbol(foo, Decl(nongenericPartialInstantiationsRelatedInBothDirections.ts, 8, 48)) + +declare let cfoo: ObjectContaining; +>cfoo : Symbol(cfoo, Decl(nongenericPartialInstantiationsRelatedInBothDirections.ts, 9, 11)) +>ObjectContaining : Symbol(ObjectContaining, Decl(nongenericPartialInstantiationsRelatedInBothDirections.ts, 4, 1)) +>Foo : Symbol(Foo, Decl(nongenericPartialInstantiationsRelatedInBothDirections.ts, 0, 0)) + +cfoo = cafoo; +>cfoo : Symbol(cfoo, Decl(nongenericPartialInstantiationsRelatedInBothDirections.ts, 9, 11)) +>cafoo : Symbol(cafoo, Decl(nongenericPartialInstantiationsRelatedInBothDirections.ts, 8, 11)) + +cafoo = cfoo; +>cafoo : Symbol(cafoo, Decl(nongenericPartialInstantiationsRelatedInBothDirections.ts, 8, 11)) +>cfoo : Symbol(cfoo, Decl(nongenericPartialInstantiationsRelatedInBothDirections.ts, 9, 11)) + diff --git a/tests/baselines/reference/nongenericPartialInstantiationsRelatedInBothDirections.types b/tests/baselines/reference/nongenericPartialInstantiationsRelatedInBothDirections.types new file mode 100644 index 00000000000..cbce9ce867b --- /dev/null +++ b/tests/baselines/reference/nongenericPartialInstantiationsRelatedInBothDirections.types @@ -0,0 +1,33 @@ +=== tests/cases/compiler/nongenericPartialInstantiationsRelatedInBothDirections.ts === +interface Foo { + a: number; +>a : number + + b: number; +>b : number + + bar: string; +>bar : string +} +interface ObjectContaining { + new (sample: Partial): Partial +>sample : Partial +} +declare let cafoo: ObjectContaining<{ a: number, foo: number }>; +>cafoo : ObjectContaining<{ a: number; foo: number; }> +>a : number +>foo : number + +declare let cfoo: ObjectContaining; +>cfoo : ObjectContaining + +cfoo = cafoo; +>cfoo = cafoo : ObjectContaining<{ a: number; foo: number; }> +>cfoo : ObjectContaining +>cafoo : ObjectContaining<{ a: number; foo: number; }> + +cafoo = cfoo; +>cafoo = cfoo : ObjectContaining +>cafoo : ObjectContaining<{ a: number; foo: number; }> +>cfoo : ObjectContaining + diff --git a/tests/baselines/reference/recursiveTypeComparison.errors.txt b/tests/baselines/reference/recursiveTypeComparison.errors.txt deleted file mode 100644 index f647763b2e2..00000000000 --- a/tests/baselines/reference/recursiveTypeComparison.errors.txt +++ /dev/null @@ -1,27 +0,0 @@ -tests/cases/compiler/recursiveTypeComparison.ts(14,5): error TS2322: Type 'Observable<{}>' is not assignable to type 'Property'. - Types of property 'needThisOne' are incompatible. - Type 'Observable<{}>' is not assignable to type 'Observable'. - Type '{}' is not assignable to type 'number'. - - -==== tests/cases/compiler/recursiveTypeComparison.ts (1 errors) ==== - // Before fix this would take an exceeding long time to complete (#1170) - - interface Observable { - // This member can't be of type T, Property, or Observable - needThisOne: Observable; - // Add more to make it slower - expo1: Property; // 0.31 seconds in check - expo2: Property; // 3.11 seconds - expo3: Property; // 82.28 seconds - } - interface Property extends Observable { } - - var p: Observable<{}>; - var stuck: Property = p; - ~~~~~ -!!! error TS2322: Type 'Observable<{}>' is not assignable to type 'Property'. -!!! error TS2322: Types of property 'needThisOne' are incompatible. -!!! error TS2322: Type 'Observable<{}>' is not assignable to type 'Observable'. -!!! error TS2322: Type '{}' is not assignable to type 'number'. - \ No newline at end of file diff --git a/tests/baselines/reference/specedNoStackBlown.js b/tests/baselines/reference/specedNoStackBlown.js new file mode 100644 index 00000000000..034caf4d7eb --- /dev/null +++ b/tests/baselines/reference/specedNoStackBlown.js @@ -0,0 +1,47 @@ +//// [specedNoStackBlown.ts] +// Type definitions for spected 0.7 +// Project: https://github.com/25th-floor/spected +// Definitions by: Benjamin Makus +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +declare function spected = SpecValue>(spec: SPEC, input: ROOTINPUT): Result; + +type Predicate = (value: INPUT, inputs: ROOTINPUT) => boolean; + +type ErrorMsg = + | (string | number | boolean | symbol | null | undefined | object) + | ((value: INPUT, field: string) => any); + +export type Spec = [Predicate, ErrorMsg]; + +export type SpecArray = Array>; + +export type SpecFunction = [INPUT] extends [ReadonlyArray] + ? (value: INPUT) => ReadonlyArray> + : [INPUT] extends [object] + ? (value: INPUT) => SpecObject + : (value: INPUT) => SpecArray; + +export type SpecObject = Partial<{[key in keyof INPUT]: SpecValue}>; + +export type SpecValue = [INPUT] extends [ReadonlyArray] + ? SpecArray | SpecFunction + : [INPUT] extends [object] + ? SpecArray | SpecFunction | SpecObject + : SpecArray | SpecFunction; + +export type Result = {[key in keyof INPUT]: true | any[] | Result}; + +export default spected; + + +//// [specedNoStackBlown.js] +"use strict"; +// Type definitions for spected 0.7 +// Project: https://github.com/25th-floor/spected +// Definitions by: Benjamin Makus +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 +exports.__esModule = true; +exports["default"] = spected; diff --git a/tests/baselines/reference/specedNoStackBlown.symbols b/tests/baselines/reference/specedNoStackBlown.symbols new file mode 100644 index 00000000000..299e31e9808 --- /dev/null +++ b/tests/baselines/reference/specedNoStackBlown.symbols @@ -0,0 +1,158 @@ +=== tests/cases/compiler/specedNoStackBlown.ts === +// Type definitions for spected 0.7 +// Project: https://github.com/25th-floor/spected +// Definitions by: Benjamin Makus +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +declare function spected = SpecValue>(spec: SPEC, input: ROOTINPUT): Result; +>spected : Symbol(spected, Decl(specedNoStackBlown.ts, 0, 0)) +>ROOTINPUT : Symbol(ROOTINPUT, Decl(specedNoStackBlown.ts, 6, 25)) +>SPEC : Symbol(SPEC, Decl(specedNoStackBlown.ts, 6, 35)) +>SpecValue : Symbol(SpecValue, Decl(specedNoStackBlown.ts, 24, 115)) +>ROOTINPUT : Symbol(ROOTINPUT, Decl(specedNoStackBlown.ts, 6, 25)) +>ROOTINPUT : Symbol(ROOTINPUT, Decl(specedNoStackBlown.ts, 6, 25)) +>SpecValue : Symbol(SpecValue, Decl(specedNoStackBlown.ts, 24, 115)) +>ROOTINPUT : Symbol(ROOTINPUT, Decl(specedNoStackBlown.ts, 6, 25)) +>ROOTINPUT : Symbol(ROOTINPUT, Decl(specedNoStackBlown.ts, 6, 25)) +>spec : Symbol(spec, Decl(specedNoStackBlown.ts, 6, 116)) +>SPEC : Symbol(SPEC, Decl(specedNoStackBlown.ts, 6, 35)) +>input : Symbol(input, Decl(specedNoStackBlown.ts, 6, 127)) +>ROOTINPUT : Symbol(ROOTINPUT, Decl(specedNoStackBlown.ts, 6, 25)) +>Result : Symbol(Result, Decl(specedNoStackBlown.ts, 30, 75)) +>ROOTINPUT : Symbol(ROOTINPUT, Decl(specedNoStackBlown.ts, 6, 25)) +>SPEC : Symbol(SPEC, Decl(specedNoStackBlown.ts, 6, 35)) + +type Predicate = (value: INPUT, inputs: ROOTINPUT) => boolean; +>Predicate : Symbol(Predicate, Decl(specedNoStackBlown.ts, 6, 171)) +>INPUT : Symbol(INPUT, Decl(specedNoStackBlown.ts, 8, 15)) +>ROOTINPUT : Symbol(ROOTINPUT, Decl(specedNoStackBlown.ts, 8, 21)) +>value : Symbol(value, Decl(specedNoStackBlown.ts, 8, 36)) +>INPUT : Symbol(INPUT, Decl(specedNoStackBlown.ts, 8, 15)) +>inputs : Symbol(inputs, Decl(specedNoStackBlown.ts, 8, 49)) +>ROOTINPUT : Symbol(ROOTINPUT, Decl(specedNoStackBlown.ts, 8, 21)) + +type ErrorMsg = +>ErrorMsg : Symbol(ErrorMsg, Decl(specedNoStackBlown.ts, 8, 80)) +>INPUT : Symbol(INPUT, Decl(specedNoStackBlown.ts, 10, 14)) + + | (string | number | boolean | symbol | null | undefined | object) + | ((value: INPUT, field: string) => any); +>value : Symbol(value, Decl(specedNoStackBlown.ts, 12, 8)) +>INPUT : Symbol(INPUT, Decl(specedNoStackBlown.ts, 10, 14)) +>field : Symbol(field, Decl(specedNoStackBlown.ts, 12, 21)) + +export type Spec = [Predicate, ErrorMsg]; +>Spec : Symbol(Spec, Decl(specedNoStackBlown.ts, 12, 45)) +>INPUT : Symbol(INPUT, Decl(specedNoStackBlown.ts, 14, 17)) +>ROOTINPUT : Symbol(ROOTINPUT, Decl(specedNoStackBlown.ts, 14, 23)) +>Predicate : Symbol(Predicate, Decl(specedNoStackBlown.ts, 6, 171)) +>INPUT : Symbol(INPUT, Decl(specedNoStackBlown.ts, 14, 17)) +>ROOTINPUT : Symbol(ROOTINPUT, Decl(specedNoStackBlown.ts, 14, 23)) +>ErrorMsg : Symbol(ErrorMsg, Decl(specedNoStackBlown.ts, 8, 80)) +>INPUT : Symbol(INPUT, Decl(specedNoStackBlown.ts, 14, 17)) + +export type SpecArray = Array>; +>SpecArray : Symbol(SpecArray, Decl(specedNoStackBlown.ts, 14, 90)) +>INPUT : Symbol(INPUT, Decl(specedNoStackBlown.ts, 16, 22)) +>ROOTINPUT : Symbol(ROOTINPUT, Decl(specedNoStackBlown.ts, 16, 28)) +>Array : Symbol(Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>Spec : Symbol(Spec, Decl(specedNoStackBlown.ts, 12, 45)) +>INPUT : Symbol(INPUT, Decl(specedNoStackBlown.ts, 16, 22)) +>ROOTINPUT : Symbol(ROOTINPUT, Decl(specedNoStackBlown.ts, 16, 28)) + +export type SpecFunction = [INPUT] extends [ReadonlyArray] +>SpecFunction : Symbol(SpecFunction, Decl(specedNoStackBlown.ts, 16, 78)) +>INPUT : Symbol(INPUT, Decl(specedNoStackBlown.ts, 18, 25)) +>ROOTINPUT : Symbol(ROOTINPUT, Decl(specedNoStackBlown.ts, 18, 31)) +>INPUT : Symbol(INPUT, Decl(specedNoStackBlown.ts, 18, 25)) +>ReadonlyArray : Symbol(ReadonlyArray, Decl(lib.es5.d.ts, --, --)) +>U : Symbol(U, Decl(specedNoStackBlown.ts, 18, 87)) + + ? (value: INPUT) => ReadonlyArray> +>value : Symbol(value, Decl(specedNoStackBlown.ts, 19, 7)) +>INPUT : Symbol(INPUT, Decl(specedNoStackBlown.ts, 18, 25)) +>ReadonlyArray : Symbol(ReadonlyArray, Decl(lib.es5.d.ts, --, --)) +>SpecArray : Symbol(SpecArray, Decl(specedNoStackBlown.ts, 14, 90)) +>U : Symbol(U, Decl(specedNoStackBlown.ts, 18, 87)) +>ROOTINPUT : Symbol(ROOTINPUT, Decl(specedNoStackBlown.ts, 18, 31)) + + : [INPUT] extends [object] +>INPUT : Symbol(INPUT, Decl(specedNoStackBlown.ts, 18, 25)) + + ? (value: INPUT) => SpecObject +>value : Symbol(value, Decl(specedNoStackBlown.ts, 21, 11)) +>INPUT : Symbol(INPUT, Decl(specedNoStackBlown.ts, 18, 25)) +>SpecObject : Symbol(SpecObject, Decl(specedNoStackBlown.ts, 22, 56)) +>INPUT : Symbol(INPUT, Decl(specedNoStackBlown.ts, 18, 25)) +>ROOTINPUT : Symbol(ROOTINPUT, Decl(specedNoStackBlown.ts, 18, 31)) + + : (value: INPUT) => SpecArray; +>value : Symbol(value, Decl(specedNoStackBlown.ts, 22, 11)) +>INPUT : Symbol(INPUT, Decl(specedNoStackBlown.ts, 18, 25)) +>SpecArray : Symbol(SpecArray, Decl(specedNoStackBlown.ts, 14, 90)) +>INPUT : Symbol(INPUT, Decl(specedNoStackBlown.ts, 18, 25)) +>ROOTINPUT : Symbol(ROOTINPUT, Decl(specedNoStackBlown.ts, 18, 31)) + +export type SpecObject = Partial<{[key in keyof INPUT]: SpecValue}>; +>SpecObject : Symbol(SpecObject, Decl(specedNoStackBlown.ts, 22, 56)) +>INPUT : Symbol(INPUT, Decl(specedNoStackBlown.ts, 24, 23)) +>ROOTINPUT : Symbol(ROOTINPUT, Decl(specedNoStackBlown.ts, 24, 29)) +>Partial : Symbol(Partial, Decl(lib.es5.d.ts, --, --)) +>key : Symbol(key, Decl(specedNoStackBlown.ts, 24, 59)) +>INPUT : Symbol(INPUT, Decl(specedNoStackBlown.ts, 24, 23)) +>SpecValue : Symbol(SpecValue, Decl(specedNoStackBlown.ts, 24, 115)) +>INPUT : Symbol(INPUT, Decl(specedNoStackBlown.ts, 24, 23)) +>key : Symbol(key, Decl(specedNoStackBlown.ts, 24, 59)) +>ROOTINPUT : Symbol(ROOTINPUT, Decl(specedNoStackBlown.ts, 24, 29)) + +export type SpecValue = [INPUT] extends [ReadonlyArray] +>SpecValue : Symbol(SpecValue, Decl(specedNoStackBlown.ts, 24, 115)) +>INPUT : Symbol(INPUT, Decl(specedNoStackBlown.ts, 26, 22)) +>ROOTINPUT : Symbol(ROOTINPUT, Decl(specedNoStackBlown.ts, 26, 28)) +>INPUT : Symbol(INPUT, Decl(specedNoStackBlown.ts, 26, 22)) +>ReadonlyArray : Symbol(ReadonlyArray, Decl(lib.es5.d.ts, --, --)) + + ? SpecArray | SpecFunction +>SpecArray : Symbol(SpecArray, Decl(specedNoStackBlown.ts, 14, 90)) +>INPUT : Symbol(INPUT, Decl(specedNoStackBlown.ts, 26, 22)) +>ROOTINPUT : Symbol(ROOTINPUT, Decl(specedNoStackBlown.ts, 26, 28)) +>SpecFunction : Symbol(SpecFunction, Decl(specedNoStackBlown.ts, 16, 78)) +>INPUT : Symbol(INPUT, Decl(specedNoStackBlown.ts, 26, 22)) +>ROOTINPUT : Symbol(ROOTINPUT, Decl(specedNoStackBlown.ts, 26, 28)) + + : [INPUT] extends [object] +>INPUT : Symbol(INPUT, Decl(specedNoStackBlown.ts, 26, 22)) + + ? SpecArray | SpecFunction | SpecObject +>SpecArray : Symbol(SpecArray, Decl(specedNoStackBlown.ts, 14, 90)) +>INPUT : Symbol(INPUT, Decl(specedNoStackBlown.ts, 26, 22)) +>ROOTINPUT : Symbol(ROOTINPUT, Decl(specedNoStackBlown.ts, 26, 28)) +>SpecFunction : Symbol(SpecFunction, Decl(specedNoStackBlown.ts, 16, 78)) +>INPUT : Symbol(INPUT, Decl(specedNoStackBlown.ts, 26, 22)) +>ROOTINPUT : Symbol(ROOTINPUT, Decl(specedNoStackBlown.ts, 26, 28)) +>SpecObject : Symbol(SpecObject, Decl(specedNoStackBlown.ts, 22, 56)) +>INPUT : Symbol(INPUT, Decl(specedNoStackBlown.ts, 26, 22)) +>ROOTINPUT : Symbol(ROOTINPUT, Decl(specedNoStackBlown.ts, 26, 28)) + + : SpecArray | SpecFunction; +>SpecArray : Symbol(SpecArray, Decl(specedNoStackBlown.ts, 14, 90)) +>INPUT : Symbol(INPUT, Decl(specedNoStackBlown.ts, 26, 22)) +>ROOTINPUT : Symbol(ROOTINPUT, Decl(specedNoStackBlown.ts, 26, 28)) +>SpecFunction : Symbol(SpecFunction, Decl(specedNoStackBlown.ts, 16, 78)) +>INPUT : Symbol(INPUT, Decl(specedNoStackBlown.ts, 26, 22)) +>ROOTINPUT : Symbol(ROOTINPUT, Decl(specedNoStackBlown.ts, 26, 28)) + +export type Result = {[key in keyof INPUT]: true | any[] | Result}; +>Result : Symbol(Result, Decl(specedNoStackBlown.ts, 30, 75)) +>INPUT : Symbol(INPUT, Decl(specedNoStackBlown.ts, 32, 19)) +>SPEC : Symbol(SPEC, Decl(specedNoStackBlown.ts, 32, 25)) +>key : Symbol(key, Decl(specedNoStackBlown.ts, 32, 36)) +>INPUT : Symbol(INPUT, Decl(specedNoStackBlown.ts, 32, 19)) +>Result : Symbol(Result, Decl(specedNoStackBlown.ts, 30, 75)) +>INPUT : Symbol(INPUT, Decl(specedNoStackBlown.ts, 32, 19)) +>key : Symbol(key, Decl(specedNoStackBlown.ts, 32, 36)) + +export default spected; +>spected : Symbol(spected, Decl(specedNoStackBlown.ts, 0, 0)) + diff --git a/tests/baselines/reference/specedNoStackBlown.types b/tests/baselines/reference/specedNoStackBlown.types new file mode 100644 index 00000000000..654f98941df --- /dev/null +++ b/tests/baselines/reference/specedNoStackBlown.types @@ -0,0 +1,64 @@ +=== tests/cases/compiler/specedNoStackBlown.ts === +// Type definitions for spected 0.7 +// Project: https://github.com/25th-floor/spected +// Definitions by: Benjamin Makus +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +declare function spected = SpecValue>(spec: SPEC, input: ROOTINPUT): Result; +>spected : = SpecValue>(spec: SPEC, input: ROOTINPUT) => Result +>spec : SPEC +>input : ROOTINPUT + +type Predicate = (value: INPUT, inputs: ROOTINPUT) => boolean; +>Predicate : Predicate +>value : INPUT +>inputs : ROOTINPUT + +type ErrorMsg = +>ErrorMsg : ErrorMsg + + | (string | number | boolean | symbol | null | undefined | object) +>null : null + + | ((value: INPUT, field: string) => any); +>value : INPUT +>field : string + +export type Spec = [Predicate, ErrorMsg]; +>Spec : [Predicate, ErrorMsg] + +export type SpecArray = Array>; +>SpecArray : [Predicate, ErrorMsg][] + +export type SpecFunction = [INPUT] extends [ReadonlyArray] +>SpecFunction : SpecFunction + + ? (value: INPUT) => ReadonlyArray> +>value : INPUT + + : [INPUT] extends [object] + ? (value: INPUT) => SpecObject +>value : INPUT + + : (value: INPUT) => SpecArray; +>value : INPUT + +export type SpecObject = Partial<{[key in keyof INPUT]: SpecValue}>; +>SpecObject : Partial<{ [key in keyof INPUT]: SpecValue; }> + +export type SpecValue = [INPUT] extends [ReadonlyArray] +>SpecValue : SpecValue + + ? SpecArray | SpecFunction + : [INPUT] extends [object] + ? SpecArray | SpecFunction | SpecObject + : SpecArray | SpecFunction; + +export type Result = {[key in keyof INPUT]: true | any[] | Result}; +>Result : Result +>true : true + +export default spected; +>spected : = SpecValue>(spec: SPEC, input: ROOTINPUT) => Result + diff --git a/tests/baselines/reference/strictFunctionTypesErrors.errors.txt b/tests/baselines/reference/strictFunctionTypesErrors.errors.txt index 3ff04c44fb7..d24b88a7a94 100644 --- a/tests/baselines/reference/strictFunctionTypesErrors.errors.txt +++ b/tests/baselines/reference/strictFunctionTypesErrors.errors.txt @@ -62,13 +62,9 @@ tests/cases/compiler/strictFunctionTypesErrors.ts(84,1): error TS2322: Type 'Fun tests/cases/compiler/strictFunctionTypesErrors.ts(111,1): error TS2322: Type 'Comparer2' is not assignable to type 'Comparer2'. Property 'dog' is missing in type 'Animal' but required in type 'Dog'. tests/cases/compiler/strictFunctionTypesErrors.ts(126,1): error TS2322: Type 'Crate' is not assignable to type 'Crate'. - Types of property 'onSetItem' are incompatible. - Type '(item: Dog) => void' is not assignable to type '(item: Animal) => void'. - Types of parameters 'item' and 'item' are incompatible. - Type 'Animal' is not assignable to type 'Dog'. + Type 'Animal' is not assignable to type 'Dog'. tests/cases/compiler/strictFunctionTypesErrors.ts(127,1): error TS2322: Type 'Crate' is not assignable to type 'Crate'. - Types of property 'item' are incompatible. - Type 'Animal' is not assignable to type 'Dog'. + Type 'Animal' is not assignable to type 'Dog'. tests/cases/compiler/strictFunctionTypesErrors.ts(133,1): error TS2322: Type '(f: (x: Dog) => Dog) => void' is not assignable to type '(f: (x: Animal) => Animal) => void'. Types of parameters 'f' and 'f' are incompatible. Type 'Animal' is not assignable to type 'Dog'. @@ -308,15 +304,11 @@ tests/cases/compiler/strictFunctionTypesErrors.ts(155,5): error TS2322: Type '(c animalCrate = dogCrate; // Error ~~~~~~~~~~~ !!! error TS2322: Type 'Crate' is not assignable to type 'Crate'. -!!! error TS2322: Types of property 'onSetItem' are incompatible. -!!! error TS2322: Type '(item: Dog) => void' is not assignable to type '(item: Animal) => void'. -!!! error TS2322: Types of parameters 'item' and 'item' are incompatible. -!!! error TS2322: Type 'Animal' is not assignable to type 'Dog'. +!!! error TS2322: Type 'Animal' is not assignable to type 'Dog'. dogCrate = animalCrate; // Error ~~~~~~~~ !!! error TS2322: Type 'Crate' is not assignable to type 'Crate'. -!!! error TS2322: Types of property 'item' are incompatible. -!!! error TS2322: Type 'Animal' is not assignable to type 'Dog'. +!!! error TS2322: Type 'Animal' is not assignable to type 'Dog'. // Verify that callback parameters are strictly checked diff --git a/tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign.errors.txt b/tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign.errors.txt deleted file mode 100644 index 47f97958f0d..00000000000 --- a/tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign.errors.txt +++ /dev/null @@ -1,82 +0,0 @@ -tests/cases/compiler/varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts(63,6): error TS2345: Argument of type 'NeededInfo>' is not assignable to parameter of type 'NeededInfo<{}>'. - Types of property 'ASchema' are incompatible. - Type 'ToA>' is not assignable to type 'ToA<{}>'. - Type '{}' is not assignable to type 'ToB<{ initialize: any; }>'. -tests/cases/compiler/varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts(66,38): error TS2344: Type 'NeededInfo>' does not satisfy the constraint 'NeededInfo<{}>'. - - -==== tests/cases/compiler/varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts (2 errors) ==== - type Either = Left | Right; - - class Left { - readonly _tag: 'Left' = 'Left' - readonly _A!: A - readonly _L!: L - constructor(readonly value: L) {} - /** The given function is applied if this is a `Right` */ - map(f: (a: A) => B): Either { - return this as any - } - ap(fab: Either B>): Either { - return null as any - } - } - - class Right { - readonly _tag: 'Right' = 'Right' - readonly _A!: A - readonly _L!: L - constructor(readonly value: A) {} - map(f: (a: A) => B): Either { - return new Right(f(this.value)) - } - ap(fab: Either B>): Either { - return null as any; - } - } - - class Type { - readonly _A!: A; - readonly _O!: O; - readonly _I!: I; - constructor( - /** a unique name for this codec */ - readonly name: string, - /** a custom type guard */ - readonly is: (u: unknown) => u is A, - /** succeeds if a value of type I can be decoded to a value of type A */ - readonly validate: (input: I, context: {}[]) => Either<{}[], A>, - /** converts a value of type A to a value of type O */ - readonly encode: (a: A) => O - ) {} - /** a version of `validate` with a default context */ - decode(i: I): Either<{}[], A> { return null as any; } - } - - interface Any extends Type {} - - type TypeOf = C["_A"]; - - type ToB = { [k in keyof S]: TypeOf }; - type ToA = { [k in keyof S]: Type }; - - type NeededInfo = { - ASchema: ToA; - }; - - export type MyInfo = NeededInfo>; - - const tmp1: MyInfo = null!; - function tmp2(n: N) {} - tmp2(tmp1); // uncommenting this line removes a type error from a completely unrelated line ?? - ~~~~ -!!! error TS2345: Argument of type 'NeededInfo>' is not assignable to parameter of type 'NeededInfo<{}>'. -!!! error TS2345: Types of property 'ASchema' are incompatible. -!!! error TS2345: Type 'ToA>' is not assignable to type 'ToA<{}>'. -!!! error TS2345: Type '{}' is not assignable to type 'ToB<{ initialize: any; }>'. -!!! related TS2728 tests/cases/compiler/varianceProblingAndZeroOrderIndexSignatureRelationsAlign.ts:59:39: 'initialize' is declared here. - - class Server {} - export class MyServer extends Server {} // not assignable error at `MyInfo` - ~~~~~~ -!!! error TS2344: Type 'NeededInfo>' does not satisfy the constraint 'NeededInfo<{}>'. \ No newline at end of file diff --git a/tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign.types b/tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign.types index d360372d5aa..f6342d442ee 100644 --- a/tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign.types +++ b/tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign.types @@ -155,7 +155,7 @@ function tmp2(n: N) {} >n : N tmp2(tmp1); // uncommenting this line removes a type error from a completely unrelated line ?? ->tmp2(tmp1) : any +>tmp2(tmp1) : void >tmp2 : >(n: N) => void >tmp1 : NeededInfo> diff --git a/tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.errors.txt b/tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.errors.txt deleted file mode 100644 index aba1bc1db66..00000000000 --- a/tests/baselines/reference/varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.errors.txt +++ /dev/null @@ -1,79 +0,0 @@ -tests/cases/compiler/varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts(66,38): error TS2344: Type 'NeededInfo>' does not satisfy the constraint 'NeededInfo<{}>'. - Types of property 'ASchema' are incompatible. - Type 'ToA>' is not assignable to type 'ToA<{}>'. - Type '{}' is not assignable to type 'ToB<{ initialize: any; }>'. - - -==== tests/cases/compiler/varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts (1 errors) ==== - type Either = Left | Right; - - class Left { - readonly _tag: 'Left' = 'Left' - readonly _A!: A - readonly _L!: L - constructor(readonly value: L) {} - /** The given function is applied if this is a `Right` */ - map(f: (a: A) => B): Either { - return this as any - } - ap(fab: Either B>): Either { - return null as any - } - } - - class Right { - readonly _tag: 'Right' = 'Right' - readonly _A!: A - readonly _L!: L - constructor(readonly value: A) {} - map(f: (a: A) => B): Either { - return new Right(f(this.value)) - } - ap(fab: Either B>): Either { - return null as any; - } - } - - class Type { - readonly _A!: A; - readonly _O!: O; - readonly _I!: I; - constructor( - /** a unique name for this codec */ - readonly name: string, - /** a custom type guard */ - readonly is: (u: unknown) => u is A, - /** succeeds if a value of type I can be decoded to a value of type A */ - readonly validate: (input: I, context: {}[]) => Either<{}[], A>, - /** converts a value of type A to a value of type O */ - readonly encode: (a: A) => O - ) {} - /** a version of `validate` with a default context */ - decode(i: I): Either<{}[], A> { return null as any; } - } - - interface Any extends Type {} - - type TypeOf = C["_A"]; - - type ToB = { [k in keyof S]: TypeOf }; - type ToA = { [k in keyof S]: Type }; - - type NeededInfo = { - ASchema: ToA; - }; - - export type MyInfo = NeededInfo>; - - const tmp1: MyInfo = null!; - function tmp2(n: N) {} - // tmp2(tmp1); // uncommenting this line removes a type error from a completely unrelated line ?? (see test 1, needs to behave the same) - - class Server {} - export class MyServer extends Server {} // not assignable error at `MyInfo` - ~~~~~~ -!!! error TS2344: Type 'NeededInfo>' does not satisfy the constraint 'NeededInfo<{}>'. -!!! error TS2344: Types of property 'ASchema' are incompatible. -!!! error TS2344: Type 'ToA>' is not assignable to type 'ToA<{}>'. -!!! error TS2344: Type '{}' is not assignable to type 'ToB<{ initialize: any; }>'. -!!! related TS2728 tests/cases/compiler/varianceProblingAndZeroOrderIndexSignatureRelationsAlign2.ts:59:39: 'initialize' is declared here. \ No newline at end of file diff --git a/tests/cases/compiler/nongenericPartialInstantiationsRelatedInBothDirections.ts b/tests/cases/compiler/nongenericPartialInstantiationsRelatedInBothDirections.ts new file mode 100644 index 00000000000..ece5187738c --- /dev/null +++ b/tests/cases/compiler/nongenericPartialInstantiationsRelatedInBothDirections.ts @@ -0,0 +1,12 @@ +interface Foo { + a: number; + b: number; + bar: string; +} +interface ObjectContaining { + new (sample: Partial): Partial +} +declare let cafoo: ObjectContaining<{ a: number, foo: number }>; +declare let cfoo: ObjectContaining; +cfoo = cafoo; +cafoo = cfoo; diff --git a/tests/cases/compiler/specedNoStackBlown.ts b/tests/cases/compiler/specedNoStackBlown.ts new file mode 100644 index 00000000000..9ada3ce1c55 --- /dev/null +++ b/tests/cases/compiler/specedNoStackBlown.ts @@ -0,0 +1,35 @@ +// Type definitions for spected 0.7 +// Project: https://github.com/25th-floor/spected +// Definitions by: Benjamin Makus +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +declare function spected = SpecValue>(spec: SPEC, input: ROOTINPUT): Result; + +type Predicate = (value: INPUT, inputs: ROOTINPUT) => boolean; + +type ErrorMsg = + | (string | number | boolean | symbol | null | undefined | object) + | ((value: INPUT, field: string) => any); + +export type Spec = [Predicate, ErrorMsg]; + +export type SpecArray = Array>; + +export type SpecFunction = [INPUT] extends [ReadonlyArray] + ? (value: INPUT) => ReadonlyArray> + : [INPUT] extends [object] + ? (value: INPUT) => SpecObject + : (value: INPUT) => SpecArray; + +export type SpecObject = Partial<{[key in keyof INPUT]: SpecValue}>; + +export type SpecValue = [INPUT] extends [ReadonlyArray] + ? SpecArray | SpecFunction + : [INPUT] extends [object] + ? SpecArray | SpecFunction | SpecObject + : SpecArray | SpecFunction; + +export type Result = {[key in keyof INPUT]: true | any[] | Result}; + +export default spected; From be2db9db12bd58f02d78f8a906f98f5ee9527663 Mon Sep 17 00:00:00 2001 From: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com> Date: Wed, 27 Feb 2019 14:14:34 -0800 Subject: [PATCH 127/149] Add globalThis (#29332) * Restore original code from bind-toplevel-this With one or two additional comments * Working in JS, but the symbol is not right. Still need to 1. Make it work in Typescript. 2. Add test (and make them work) for the other uses of GlobalThis: window, globalThis, etc. * Check in TS also; update some tests Lots of tests still fail, but all but 1 change so far has been correct. * Update baselines A couple of tests still fail and need to be fixed. * Handle type references to globalThis The type reference must be `typeof globalThis`. Just `globalThis` will be treated as a value reference in type position -- an error. * Restore former behaviour of implicitThis errors I left the noImplicitThis rule for captured use of global this in an arrow function, even though technically it isn't `any` any more -- it's typeof globalThis. However, you should still use some other method to access globals inside an arrow, because captured-global-this is super confusing there. * Test values with type globalThis I ran into a problem with intersecting `Window & typeof globalThis`: 1. This adds a new index signature to Window, which is probably not desired. In fact, with noImplicitAny, it's not desired on globalThis either I think. 2. Adding this type requires editing TSJS-lib-generator, not this repo. So I added the test cases and will probably update them later, when those two problems are fixed. * Add esnext declaration for globalThis * Switch to symbol-based approach I decided I didn't like the import-type-based approach. Update baselines to reflect the difference. * Do not suggest globals for completions at toplevel * Add tests of element and property access * Look up globalThis using normal resolution globalThis is no longer constructed lazily. Its synthetic Identifier node is also now more realistic. * Update fourslash tests * Add missed fourslash test update * Remove esnext.globalthis.d.ts too * Add chained globalThis self-lookup test * Attempt at making globalThis readonly In progress, had to interrupt for other work. * Add/update tests * Addres PR comments: 1. Add parameter to tryGetThisTypeAt to exclude globalThis. 2. Use combined Module flag instead combining them in-place. 3. SymbolDisplay doesn't print 'module globalThis' for this expressions anymore. --- src/compiler/binder.ts | 9 +- src/compiler/checker.ts | 59 ++++-- src/compiler/diagnosticMessages.json | 2 +- src/compiler/types.ts | 2 +- src/harness/fourslash.ts | 18 +- src/services/completions.ts | 2 +- src/services/symbolDisplay.ts | 2 +- src/testRunner/unittests/tsserver/projects.ts | 3 +- .../reference/assignmentLHSIsValue.symbols | 2 + .../reference/assignmentLHSIsValue.types | 6 +- .../castExpressionParentheses.symbols | 4 + .../reference/castExpressionParentheses.types | 4 +- ...sionThisExpressionAndAliasInGlobal.symbols | 1 + ...lisionThisExpressionAndAliasInGlobal.types | 6 +- ...sExpressionAndAmbientClassInGlobal.symbols | 1 + ...hisExpressionAndAmbientClassInGlobal.types | 6 +- ...hisExpressionAndAmbientVarInGlobal.symbols | 1 + ...nThisExpressionAndAmbientVarInGlobal.types | 6 +- ...sionThisExpressionAndClassInGlobal.symbols | 1 + ...lisionThisExpressionAndClassInGlobal.types | 6 +- ...isionThisExpressionAndEnumInGlobal.symbols | 1 + ...llisionThisExpressionAndEnumInGlobal.types | 6 +- ...nThisExpressionAndFunctionInGlobal.symbols | 1 + ...ionThisExpressionAndFunctionInGlobal.types | 6 +- ...nThisExpressionAndLocalVarInLambda.symbols | 1 + ...ionThisExpressionAndLocalVarInLambda.types | 2 +- ...ionThisExpressionAndModuleInGlobal.symbols | 1 + ...isionThisExpressionAndModuleInGlobal.types | 6 +- ...lisionThisExpressionAndVarInGlobal.symbols | 1 + ...ollisionThisExpressionAndVarInGlobal.types | 6 +- .../reference/commentsInterface.symbols | 6 + .../reference/commentsInterface.types | 12 +- .../compoundAssignmentLHSIsValue.errors.txt | 8 +- .../compoundAssignmentLHSIsValue.symbols | 4 + .../compoundAssignmentLHSIsValue.types | 12 +- ...onentiationAssignmentLHSIsValue.errors.txt | 8 +- ...ExponentiationAssignmentLHSIsValue.symbols | 2 + ...ndExponentiationAssignmentLHSIsValue.types | 6 +- .../computedPropertyNames20_ES5.symbols | 1 + .../computedPropertyNames20_ES5.types | 2 +- .../computedPropertyNames20_ES6.symbols | 1 + .../computedPropertyNames20_ES6.types | 2 +- ...ructorWithIncompleteTypeAnnotation.symbols | 1 + ...structorWithIncompleteTypeAnnotation.types | 2 +- .../emitArrowFunctionThisCapturing.errors.txt | 20 ++ .../emitArrowFunctionThisCapturing.symbols | 7 + .../emitArrowFunctionThisCapturing.types | 6 +- ...itArrowFunctionThisCapturingES6.errors.txt | 20 ++ .../emitArrowFunctionThisCapturingES6.symbols | 7 + .../emitArrowFunctionThisCapturingES6.types | 6 +- ...CapturingThisInTupleDestructuring1.symbols | 3 + ...itCapturingThisInTupleDestructuring1.types | 6 +- .../reference/globalThisCapture.symbols | 3 + .../reference/globalThisCapture.types | 10 +- .../globalThisPropertyAssignment.errors.txt | 13 ++ .../globalThisPropertyAssignment.symbols | 19 ++ .../globalThisPropertyAssignment.types | 28 +++ .../globalThisReadonlyProperties.errors.txt | 15 ++ .../reference/globalThisReadonlyProperties.js | 14 ++ .../globalThisReadonlyProperties.symbols | 22 ++ .../globalThisReadonlyProperties.types | 31 +++ .../reference/globalThisTypeIndexAccess.js | 5 + .../globalThisTypeIndexAccess.symbols | 5 + .../reference/globalThisTypeIndexAccess.types | 5 + .../reference/globalThisUnknown.errors.txt | 20 ++ .../baselines/reference/globalThisUnknown.js | 26 +++ .../reference/globalThisUnknown.symbols | 28 +++ .../reference/globalThisUnknown.types | 39 ++++ .../globalThisUnknownNoImplicitAny.errors.txt | 32 +++ .../globalThisUnknownNoImplicitAny.js | 21 ++ .../globalThisUnknownNoImplicitAny.symbols | 25 +++ .../globalThisUnknownNoImplicitAny.types | 36 ++++ .../globalThisVarDeclaration.errors.txt | 69 ++++++ .../reference/globalThisVarDeclaration.js | 59 ++++++ .../globalThisVarDeclaration.symbols | 87 ++++++++ .../reference/globalThisVarDeclaration.types | 113 ++++++++++ .../reference/implicitAnyInCatch.symbols | 1 + .../reference/implicitAnyInCatch.types | 2 +- ...neJsxFactoryDeclarationsLocalTypes.symbols | 1 + ...lineJsxFactoryDeclarationsLocalTypes.types | 2 +- ...jsxAttributeWithoutExpressionReact.symbols | 1 + .../jsxAttributeWithoutExpressionReact.types | 2 +- .../reference/jsxReactTestSuite.symbols | 5 + .../reference/jsxReactTestSuite.types | 6 +- ...pertyAccessAndArrowFunctionIndent1.symbols | 3 + ...ropertyAccessAndArrowFunctionIndent1.types | 4 +- .../noImplicitThisFunctions.errors.txt | 8 +- .../reference/noImplicitThisFunctions.symbols | 2 + .../reference/noImplicitThisFunctions.types | 10 +- .../parserCommaInTypeMemberList2.symbols | 1 + .../parserCommaInTypeMemberList2.types | 2 +- .../parserConditionalExpression1.symbols | 5 +- .../parserConditionalExpression1.types | 6 +- .../reference/parserForStatement8.errors.txt | 4 +- .../reference/parserForStatement8.symbols | 4 +- .../reference/parserForStatement8.types | 2 +- .../parserModifierOnStatementInBlock2.symbols | 1 + .../parserModifierOnStatementInBlock2.types | 4 +- .../reference/parserStrictMode16.symbols | 11 +- .../reference/parserStrictMode16.types | 2 +- .../parserUnaryExpression1.errors.txt | 4 +- .../reference/parserUnaryExpression1.symbols | 3 +- .../reference/parserUnaryExpression1.types | 2 +- .../reference/propertyWrappedInTry.symbols | 1 + .../reference/propertyWrappedInTry.types | 2 +- .../thisInInvalidContexts.errors.txt | 5 +- .../reference/thisInInvalidContexts.symbols | 1 + .../reference/thisInInvalidContexts.types | 2 +- ...InInvalidContextsExternalModule.errors.txt | 5 +- ...hisInInvalidContextsExternalModule.symbols | 1 + .../thisInInvalidContextsExternalModule.types | 2 +- .../reference/thisTypeInFunctions.symbols | 11 + .../reference/thisTypeInFunctions.types | 40 ++-- .../thisTypeInFunctionsNegative.symbols | 6 + .../thisTypeInFunctionsNegative.types | 12 +- .../reference/topLevelLambda2.symbols | 3 + .../baselines/reference/topLevelLambda2.types | 8 +- .../reference/topLevelLambda3.symbols | 3 + .../baselines/reference/topLevelLambda3.types | 6 +- .../reference/topLevelLambda4.symbols | 3 + .../baselines/reference/topLevelLambda4.types | 10 +- .../reference/topLevelThisAssignment.symbols | 27 ++- .../reference/topLevelThisAssignment.types | 22 +- .../tsxAttributeResolution15.errors.txt | 5 +- .../tsxAttributeResolution15.symbols | 1 + .../reference/tsxAttributeResolution15.types | 2 +- .../tsxSpreadAttributesResolution4.symbols | 1 + .../tsxSpreadAttributesResolution4.types | 2 +- .../typeFromPropertyAssignment23.symbols | 2 + .../typeFromPropertyAssignment23.types | 2 +- .../typeFromPropertyAssignment9.symbols | 5 + .../typeFromPropertyAssignment9.types | 10 +- .../baselines/reference/typeOfThis.errors.txt | 38 +--- tests/baselines/reference/typeOfThis.js | 200 ++++++++---------- tests/baselines/reference/typeOfThis.symbols | 20 +- tests/baselines/reference/typeOfThis.types | 43 ++-- .../reference/unknownSymbols1.symbols | 1 + .../baselines/reference/unknownSymbols1.types | 2 +- .../reference/wrappedIncovations1.symbols | 1 + .../reference/wrappedIncovations1.types | 2 +- .../reference/wrappedIncovations2.symbols | 1 + .../reference/wrappedIncovations2.types | 2 +- .../es2019/globalThisPropertyAssignment.ts | 10 + .../es2019/globalThisReadonlyProperties.ts | 5 + .../es2019/globalThisTypeIndexAccess.ts | 2 + .../conformance/es2019/globalThisUnknown.ts | 13 ++ .../es2019/globalThisUnknownNoImplicitAny.ts | 11 + .../es2019/globalThisVarDeclaration.ts | 35 +++ .../expressions/thisKeyword/typeOfThis.ts | 13 +- .../salsa/topLevelThisAssignment.ts | 1 + .../completionEntryForClassMembers.ts | 1 + .../completionListIsGlobalCompletion.ts | 2 +- .../cases/fourslash/completionListKeywords.ts | 2 +- .../fourslash/completionListWithMeanings.ts | 2 + .../completionListWithModulesFromModule.ts | 4 + .../completionsImport_default_anonymous.ts | 2 +- ...ompletionsImport_exportEquals_anonymous.ts | 4 +- .../fourslash/completionsImport_keywords.ts | 2 +- .../completionsImport_multipleWithSameName.ts | 1 + ...mpletionsImport_named_didNotExistBefore.ts | 1 + ...mpletionsImport_ofAlias_preferShortPath.ts | 1 + .../completionsImport_reExportDefault.ts | 1 + .../completionsImport_shadowedByLocal.ts | 2 +- .../fourslash/completionsTypeKeywords.ts | 2 +- .../cases/fourslash/findAllRefsThisKeyword.ts | 4 +- .../findAllRefsThisKeywordMultipleFiles.ts | 2 +- .../tsxCompletionOnOpeningTagWithoutJSX1.ts | 2 +- 167 files changed, 1372 insertions(+), 400 deletions(-) create mode 100644 tests/baselines/reference/emitArrowFunctionThisCapturing.errors.txt create mode 100644 tests/baselines/reference/emitArrowFunctionThisCapturingES6.errors.txt create mode 100644 tests/baselines/reference/globalThisPropertyAssignment.errors.txt create mode 100644 tests/baselines/reference/globalThisPropertyAssignment.symbols create mode 100644 tests/baselines/reference/globalThisPropertyAssignment.types create mode 100644 tests/baselines/reference/globalThisReadonlyProperties.errors.txt create mode 100644 tests/baselines/reference/globalThisReadonlyProperties.js create mode 100644 tests/baselines/reference/globalThisReadonlyProperties.symbols create mode 100644 tests/baselines/reference/globalThisReadonlyProperties.types create mode 100644 tests/baselines/reference/globalThisTypeIndexAccess.js create mode 100644 tests/baselines/reference/globalThisTypeIndexAccess.symbols create mode 100644 tests/baselines/reference/globalThisTypeIndexAccess.types create mode 100644 tests/baselines/reference/globalThisUnknown.errors.txt create mode 100644 tests/baselines/reference/globalThisUnknown.js create mode 100644 tests/baselines/reference/globalThisUnknown.symbols create mode 100644 tests/baselines/reference/globalThisUnknown.types create mode 100644 tests/baselines/reference/globalThisUnknownNoImplicitAny.errors.txt create mode 100644 tests/baselines/reference/globalThisUnknownNoImplicitAny.js create mode 100644 tests/baselines/reference/globalThisUnknownNoImplicitAny.symbols create mode 100644 tests/baselines/reference/globalThisUnknownNoImplicitAny.types create mode 100644 tests/baselines/reference/globalThisVarDeclaration.errors.txt create mode 100644 tests/baselines/reference/globalThisVarDeclaration.js create mode 100644 tests/baselines/reference/globalThisVarDeclaration.symbols create mode 100644 tests/baselines/reference/globalThisVarDeclaration.types create mode 100644 tests/cases/conformance/es2019/globalThisPropertyAssignment.ts create mode 100644 tests/cases/conformance/es2019/globalThisReadonlyProperties.ts create mode 100644 tests/cases/conformance/es2019/globalThisTypeIndexAccess.ts create mode 100644 tests/cases/conformance/es2019/globalThisUnknown.ts create mode 100644 tests/cases/conformance/es2019/globalThisUnknownNoImplicitAny.ts create mode 100644 tests/cases/conformance/es2019/globalThisVarDeclaration.ts diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 17919a326d5..ed70444bd9b 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -2499,8 +2499,13 @@ namespace ts { declareSymbol(symbolTable, containingClass.symbol, node, SymbolFlags.Property, SymbolFlags.None, /*isReplaceableByMethod*/ true); break; case SyntaxKind.SourceFile: - // this.foo assignment in a source file - // Do not bind. It would be nice to support this someday though. + // this.property = assignment in a source file -- declare symbol in exports for a module, in locals for a script + if ((thisContainer as SourceFile).commonJsModuleIndicator) { + declareSymbol(thisContainer.symbol.exports!, thisContainer.symbol, node, SymbolFlags.Property | SymbolFlags.ExportValue, SymbolFlags.None); + } + else { + declareSymbolAndAddToSymbolTable(node, SymbolFlags.FunctionScopedVariable, SymbolFlags.FunctionScopedVariableExcludes); + } break; default: diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 247c789577c..cf61c4a97a8 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -88,8 +88,16 @@ namespace ts { const emitResolver = createResolver(); const nodeBuilder = createNodeBuilder(); + const globals = createSymbolTable(); const undefinedSymbol = createSymbol(SymbolFlags.Property, "undefined" as __String); undefinedSymbol.declarations = []; + + const globalThisSymbol = createSymbol(SymbolFlags.Module, "globalThis" as __String, CheckFlags.Readonly); + globalThisSymbol.exports = globals; + globalThisSymbol.valueDeclaration = createNode(SyntaxKind.Identifier) as Identifier; + (globalThisSymbol.valueDeclaration as Identifier).escapedText = "globalThis" as __String; + globals.set(globalThisSymbol.escapedName, globalThisSymbol); + const argumentsSymbol = createSymbol(SymbolFlags.Property, "arguments" as __String); const requireSymbol = createSymbol(SymbolFlags.Property, "require" as __String); @@ -310,9 +318,9 @@ namespace ts { getAccessibleSymbolChain, getTypePredicateOfSignature: getTypePredicateOfSignature as (signature: Signature) => TypePredicate, // TODO: GH#18217 resolveExternalModuleSymbol, - tryGetThisTypeAt: node => { + tryGetThisTypeAt: (node, includeGlobalThis) => { node = getParseTreeNode(node); - return node && tryGetThisTypeAt(node); + return node && tryGetThisTypeAt(node, includeGlobalThis); }, getTypeArgumentConstraint: nodeIn => { const node = getParseTreeNode(nodeIn, isTypeNode); @@ -459,7 +467,6 @@ namespace ts { const enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); - const globals = createSymbolTable(); interface DuplicateInfoForSymbol { readonly firstFileLocations: Node[]; readonly secondFileLocations: Node[]; @@ -9703,7 +9710,7 @@ namespace ts { } function getLiteralTypeFromProperties(type: Type, include: TypeFlags) { - return getUnionType(map(getPropertiesOfType(type), t => getLiteralTypeFromProperty(t, include))); + return getUnionType(map(getPropertiesOfType(type), p => getLiteralTypeFromProperty(p, include))); } function getNonEnumNumberIndexInfo(type: Type) { @@ -16990,25 +16997,27 @@ namespace ts { captureLexicalThis(node, container); } - const type = tryGetThisTypeAt(node, container); - if (!type && noImplicitThis) { - // With noImplicitThis, functions may not reference 'this' if it has type 'any' - const diag = error( - node, - capturedByArrowFunction && container.kind === SyntaxKind.SourceFile ? - Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this_which_implicitly_has_type_any : - Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); - if (!isSourceFile(container)) { - const outsideThis = tryGetThisTypeAt(container); - if (outsideThis) { - addRelatedInfo(diag, createDiagnosticForNode(container, Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container)); + const type = tryGetThisTypeAt(node, /*includeGlobalThis*/ true, container); + if (noImplicitThis) { + const globalThisType = getTypeOfSymbol(globalThisSymbol); + if (type === globalThisType && capturedByArrowFunction) { + error(node, Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this); + } + else if (!type) { + // With noImplicitThis, functions may not reference 'this' if it has type 'any' + const diag = error(node, Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); + if (!isSourceFile(container)) { + const outsideThis = tryGetThisTypeAt(container); + if (outsideThis && outsideThis !== globalThisType) { + addRelatedInfo(diag, createDiagnosticForNode(container, Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container)); + } } } } return type || anyType; } - function tryGetThisTypeAt(node: Node, container = getThisContainer(node, /*includeArrowFunctions*/ false)): Type | undefined { + function tryGetThisTypeAt(node: Node, includeGlobalThis = true, container = getThisContainer(node, /*includeArrowFunctions*/ false)): Type | undefined { const isInJS = isInJSFile(node); if (isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || getThisParameter(container))) { @@ -17055,6 +17064,16 @@ namespace ts { return getFlowTypeOfReference(node, type); } } + if (isSourceFile(container)) { + // look up in the source file's locals or exports + if (container.commonJsModuleIndicator) { + const fileSymbol = getSymbolOfNode(container); + return fileSymbol && getTypeOfSymbol(fileSymbol); + } + else if (includeGlobalThis) { + return getTypeOfSymbol(globalThisSymbol); + } + } } function getClassNameFromPrototypeMethod(container: Node) { @@ -19352,6 +19371,12 @@ namespace ts { if (isJSLiteralType(leftType)) { return anyType; } + if (leftType.symbol === globalThisSymbol) { + if (noImplicitAny) { + error(right, Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(leftType)); + } + return anyType; + } if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) { reportNonexistentProperty(right, leftType.flags & TypeFlags.TypeParameter && (leftType as TypeParameter).isThisType ? apparentType : leftType); } diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 09b0f721292..83483a95de1 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -4149,7 +4149,7 @@ "category": "Error", "code": 7040 }, - "The containing arrow function captures the global value of 'this' which implicitly has type 'any'.": { + "The containing arrow function captures the global value of 'this'.": { "category": "Error", "code": 7041 }, diff --git a/src/compiler/types.ts b/src/compiler/types.ts index cce869df44e..42fd1126d4c 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -3223,7 +3223,7 @@ namespace ts { */ /* @internal */ resolveExternalModuleSymbol(symbol: Symbol): Symbol; /** @param node A location where we might consider accessing `this`. Not necessarily a ThisExpression. */ - /* @internal */ tryGetThisTypeAt(node: Node): Type | undefined; + /* @internal */ tryGetThisTypeAt(node: Node, includeGlobalThis?: boolean): Type | undefined; /* @internal */ getTypeArgumentConstraint(node: TypeNode): Type | undefined; /** diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index f3a7197e777..16f1a37ae83 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -774,7 +774,7 @@ namespace FourSlash { if ("exact" in options) { ts.Debug.assert(!("includes" in options) && !("excludes" in options)); if (options.exact === undefined) throw this.raiseError("Expected no completions"); - this.verifyCompletionsAreExactly(actualCompletions.entries, toArray(options.exact)); + this.verifyCompletionsAreExactly(actualCompletions.entries, toArray(options.exact), options.marker); } else { if (options.includes) { @@ -841,14 +841,14 @@ namespace FourSlash { } } - private verifyCompletionsAreExactly(actual: ReadonlyArray, expected: ReadonlyArray) { + private verifyCompletionsAreExactly(actual: ReadonlyArray, expected: ReadonlyArray, marker?: ArrayOrSingle) { // First pass: test that names are right. Then we'll test details. - assert.deepEqual(actual.map(a => a.name), expected.map(e => typeof e === "string" ? e : e.name)); + assert.deepEqual(actual.map(a => a.name), expected.map(e => typeof e === "string" ? e : e.name), marker ? "At marker " + JSON.stringify(marker) : undefined); ts.zipWith(actual, expected, (completion, expectedCompletion, index) => { const name = typeof expectedCompletion === "string" ? expectedCompletion : expectedCompletion.name; if (completion.name !== name) { - this.raiseError(`Expected completion at index ${index} to be ${name}, got ${completion.name}`); + this.raiseError(`${marker ? JSON.stringify(marker) : "" } Expected completion at index ${index} to be ${name}, got ${completion.name}`); } this.verifyCompletionEntry(completion, expectedCompletion); }); @@ -4545,6 +4545,7 @@ namespace FourSlashInterface { export function globalTypesPlus(plus: ReadonlyArray): ReadonlyArray { return [ + { name: "globalThis", kind: "module" }, ...globalTypeDecls, ...plus, ...typeKeywords, @@ -4786,6 +4787,7 @@ namespace FourSlashInterface { export const globalsInsideFunction = (plus: ReadonlyArray): ReadonlyArray => [ { name: "arguments", kind: "local var" }, ...plus, + { name: "globalThis", kind: "module" }, ...globalsVars, { name: "undefined", kind: "var" }, ...globalKeywordsInsideFunction, @@ -4921,13 +4923,19 @@ namespace FourSlashInterface { })(); export const globals: ReadonlyArray = [ + { name: "globalThis", kind: "module" }, ...globalsVars, { name: "undefined", kind: "var" }, ...globalKeywords ]; export function globalsPlus(plus: ReadonlyArray): ReadonlyArray { - return [...globalsVars, ...plus, { name: "undefined", kind: "var" }, ...globalKeywords]; + return [ + { name: "globalThis", kind: "module" }, + ...globalsVars, + ...plus, + { name: "undefined", kind: "var" }, + ...globalKeywords]; } } diff --git a/src/services/completions.ts b/src/services/completions.ts index f17ee862cca..a070bf8f7c1 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -1030,7 +1030,7 @@ namespace ts.Completions { // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` if (preferences.includeCompletionsWithInsertText && scopeNode.kind !== SyntaxKind.SourceFile) { - const thisType = typeChecker.tryGetThisTypeAt(scopeNode); + const thisType = typeChecker.tryGetThisTypeAt(scopeNode, /*includeGlobalThis*/ false); if (thisType) { for (const symbol of getPropertiesForCompletion(thisType, typeChecker)) { symbolToOriginInfoMap[getSymbolId(symbol)] = { kind: SymbolOriginInfoKind.ThisType }; diff --git a/src/services/symbolDisplay.ts b/src/services/symbolDisplay.ts index e0728f98a29..1c710b8cd78 100644 --- a/src/services/symbolDisplay.ts +++ b/src/services/symbolDisplay.ts @@ -310,7 +310,7 @@ namespace ts.SymbolDisplay { displayParts.push(spacePart()); addFullSymbolName(symbol); } - if (symbolFlags & SymbolFlags.Module) { + if (symbolFlags & SymbolFlags.Module && !isThisExpression) { prefixNextMeaning(); const declaration = getDeclarationOfKind(symbol, SyntaxKind.ModuleDeclaration); const isNamespace = declaration && declaration.name && declaration.name.kind === SyntaxKind.Identifier; diff --git a/src/testRunner/unittests/tsserver/projects.ts b/src/testRunner/unittests/tsserver/projects.ts index 3a648c9189e..264dbff285e 100644 --- a/src/testRunner/unittests/tsserver/projects.ts +++ b/src/testRunner/unittests/tsserver/projects.ts @@ -708,7 +708,8 @@ namespace ts.projectSystem { // Check identifiers defined in HTML content are available in .ts file const project = configuredProjectAt(projectService, 0); let completions = project.getLanguageService().getCompletionsAtPosition(file1.path, 1, emptyOptions); - assert(completions && completions.entries[0].name === "hello", `expected entry hello to be in completion list`); + assert(completions && completions.entries[1].name === "hello", `expected entry hello to be in completion list`); + assert(completions && completions.entries[0].name === "globalThis", `first entry should be globalThis (not strictly relevant for this test).`); // Close HTML file projectService.applyChangesInOpenFiles( diff --git a/tests/baselines/reference/assignmentLHSIsValue.symbols b/tests/baselines/reference/assignmentLHSIsValue.symbols index 17925257dfb..aad2ec2ed95 100644 --- a/tests/baselines/reference/assignmentLHSIsValue.symbols +++ b/tests/baselines/reference/assignmentLHSIsValue.symbols @@ -27,6 +27,7 @@ function foo() { this = value; } >value : Symbol(value, Decl(assignmentLHSIsValue.ts, 1, 3)) this = value; +>this : Symbol(globalThis) >value : Symbol(value, Decl(assignmentLHSIsValue.ts, 1, 3)) // identifiers: module, class, enum, function @@ -116,6 +117,7 @@ foo() = value; // parentheses, the containted expression is value (this) = value; +>this : Symbol(globalThis) >value : Symbol(value, Decl(assignmentLHSIsValue.ts, 1, 3)) (M) = value; diff --git a/tests/baselines/reference/assignmentLHSIsValue.types b/tests/baselines/reference/assignmentLHSIsValue.types index b35c15bfe23..81fd5dc537b 100644 --- a/tests/baselines/reference/assignmentLHSIsValue.types +++ b/tests/baselines/reference/assignmentLHSIsValue.types @@ -33,7 +33,7 @@ function foo() { this = value; } this = value; >this = value : any ->this : any +>this : typeof globalThis >value : any // identifiers: module, class, enum, function @@ -159,8 +159,8 @@ foo() = value; // parentheses, the containted expression is value (this) = value; >(this) = value : any ->(this) : any ->this : any +>(this) : typeof globalThis +>this : typeof globalThis >value : any (M) = value; diff --git a/tests/baselines/reference/castExpressionParentheses.symbols b/tests/baselines/reference/castExpressionParentheses.symbols index df7ef6a1f2f..ebc326e0a85 100644 --- a/tests/baselines/reference/castExpressionParentheses.symbols +++ b/tests/baselines/reference/castExpressionParentheses.symbols @@ -21,7 +21,11 @@ declare var a; (null); // names and dotted names (this); +>this : Symbol(globalThis) + (this.x); +>this : Symbol(globalThis) + ((a).x); >a : Symbol(a, Decl(castExpressionParentheses.ts, 0, 11)) diff --git a/tests/baselines/reference/castExpressionParentheses.types b/tests/baselines/reference/castExpressionParentheses.types index db38aad5a47..a2d789577a0 100644 --- a/tests/baselines/reference/castExpressionParentheses.types +++ b/tests/baselines/reference/castExpressionParentheses.types @@ -77,13 +77,13 @@ declare var a; (this); >(this) : any >this : any ->this : any +>this : typeof globalThis (this.x); >(this.x) : any >this.x : any >this.x : any ->this : any +>this : typeof globalThis >x : any ((a).x); diff --git a/tests/baselines/reference/collisionThisExpressionAndAliasInGlobal.symbols b/tests/baselines/reference/collisionThisExpressionAndAliasInGlobal.symbols index b8904c087b3..29cb9d44b49 100644 --- a/tests/baselines/reference/collisionThisExpressionAndAliasInGlobal.symbols +++ b/tests/baselines/reference/collisionThisExpressionAndAliasInGlobal.symbols @@ -7,6 +7,7 @@ module a { } var f = () => this; >f : Symbol(f, Decl(collisionThisExpressionAndAliasInGlobal.ts, 3, 3)) +>this : Symbol(globalThis) import _this = a; // Error >_this : Symbol(_this, Decl(collisionThisExpressionAndAliasInGlobal.ts, 3, 19)) diff --git a/tests/baselines/reference/collisionThisExpressionAndAliasInGlobal.types b/tests/baselines/reference/collisionThisExpressionAndAliasInGlobal.types index 2bc6c890319..1a4b1c91821 100644 --- a/tests/baselines/reference/collisionThisExpressionAndAliasInGlobal.types +++ b/tests/baselines/reference/collisionThisExpressionAndAliasInGlobal.types @@ -7,9 +7,9 @@ module a { >10 : 10 } var f = () => this; ->f : () => any ->() => this : () => any ->this : any +>f : () => typeof globalThis +>() => this : () => typeof globalThis +>this : typeof globalThis import _this = a; // Error >_this : typeof a diff --git a/tests/baselines/reference/collisionThisExpressionAndAmbientClassInGlobal.symbols b/tests/baselines/reference/collisionThisExpressionAndAmbientClassInGlobal.symbols index 71aaa26e2ea..ba225612d73 100644 --- a/tests/baselines/reference/collisionThisExpressionAndAmbientClassInGlobal.symbols +++ b/tests/baselines/reference/collisionThisExpressionAndAmbientClassInGlobal.symbols @@ -4,6 +4,7 @@ declare class _this { // no error - as no code generation } var f = () => this; >f : Symbol(f, Decl(collisionThisExpressionAndAmbientClassInGlobal.ts, 2, 3)) +>this : Symbol(globalThis) var a = new _this(); // Error >a : Symbol(a, Decl(collisionThisExpressionAndAmbientClassInGlobal.ts, 3, 3)) diff --git a/tests/baselines/reference/collisionThisExpressionAndAmbientClassInGlobal.types b/tests/baselines/reference/collisionThisExpressionAndAmbientClassInGlobal.types index ea0c8505fa0..886e0c70eea 100644 --- a/tests/baselines/reference/collisionThisExpressionAndAmbientClassInGlobal.types +++ b/tests/baselines/reference/collisionThisExpressionAndAmbientClassInGlobal.types @@ -3,9 +3,9 @@ declare class _this { // no error - as no code generation >_this : _this } var f = () => this; ->f : () => any ->() => this : () => any ->this : any +>f : () => typeof globalThis +>() => this : () => typeof globalThis +>this : typeof globalThis var a = new _this(); // Error >a : _this diff --git a/tests/baselines/reference/collisionThisExpressionAndAmbientVarInGlobal.symbols b/tests/baselines/reference/collisionThisExpressionAndAmbientVarInGlobal.symbols index 859234b35fa..702a8300c36 100644 --- a/tests/baselines/reference/collisionThisExpressionAndAmbientVarInGlobal.symbols +++ b/tests/baselines/reference/collisionThisExpressionAndAmbientVarInGlobal.symbols @@ -4,6 +4,7 @@ declare var _this: number; // no error as no code gen var f = () => this; >f : Symbol(f, Decl(collisionThisExpressionAndAmbientVarInGlobal.ts, 1, 3)) +>this : Symbol(globalThis) _this = 10; // Error >_this : Symbol(_this, Decl(collisionThisExpressionAndAmbientVarInGlobal.ts, 0, 11)) diff --git a/tests/baselines/reference/collisionThisExpressionAndAmbientVarInGlobal.types b/tests/baselines/reference/collisionThisExpressionAndAmbientVarInGlobal.types index c4038602bba..ed58281dfd6 100644 --- a/tests/baselines/reference/collisionThisExpressionAndAmbientVarInGlobal.types +++ b/tests/baselines/reference/collisionThisExpressionAndAmbientVarInGlobal.types @@ -3,9 +3,9 @@ declare var _this: number; // no error as no code gen >_this : number var f = () => this; ->f : () => any ->() => this : () => any ->this : any +>f : () => typeof globalThis +>() => this : () => typeof globalThis +>this : typeof globalThis _this = 10; // Error >_this = 10 : 10 diff --git a/tests/baselines/reference/collisionThisExpressionAndClassInGlobal.symbols b/tests/baselines/reference/collisionThisExpressionAndClassInGlobal.symbols index 73781af4894..ba749b89ad0 100644 --- a/tests/baselines/reference/collisionThisExpressionAndClassInGlobal.symbols +++ b/tests/baselines/reference/collisionThisExpressionAndClassInGlobal.symbols @@ -4,4 +4,5 @@ class _this { } var f = () => this; >f : Symbol(f, Decl(collisionThisExpressionAndClassInGlobal.ts, 2, 3)) +>this : Symbol(globalThis) diff --git a/tests/baselines/reference/collisionThisExpressionAndClassInGlobal.types b/tests/baselines/reference/collisionThisExpressionAndClassInGlobal.types index 5e4cd6e0ab4..f68d4212c1f 100644 --- a/tests/baselines/reference/collisionThisExpressionAndClassInGlobal.types +++ b/tests/baselines/reference/collisionThisExpressionAndClassInGlobal.types @@ -3,7 +3,7 @@ class _this { >_this : _this } var f = () => this; ->f : () => any ->() => this : () => any ->this : any +>f : () => typeof globalThis +>() => this : () => typeof globalThis +>this : typeof globalThis diff --git a/tests/baselines/reference/collisionThisExpressionAndEnumInGlobal.symbols b/tests/baselines/reference/collisionThisExpressionAndEnumInGlobal.symbols index 022b6487d02..88723692ffd 100644 --- a/tests/baselines/reference/collisionThisExpressionAndEnumInGlobal.symbols +++ b/tests/baselines/reference/collisionThisExpressionAndEnumInGlobal.symbols @@ -10,4 +10,5 @@ enum _this { // Error } var f = () => this; >f : Symbol(f, Decl(collisionThisExpressionAndEnumInGlobal.ts, 4, 3)) +>this : Symbol(globalThis) diff --git a/tests/baselines/reference/collisionThisExpressionAndEnumInGlobal.types b/tests/baselines/reference/collisionThisExpressionAndEnumInGlobal.types index 87a28ada0e2..5be7877f4e9 100644 --- a/tests/baselines/reference/collisionThisExpressionAndEnumInGlobal.types +++ b/tests/baselines/reference/collisionThisExpressionAndEnumInGlobal.types @@ -9,7 +9,7 @@ enum _this { // Error >_thisVal2 : _this._thisVal2 } var f = () => this; ->f : () => any ->() => this : () => any ->this : any +>f : () => typeof globalThis +>() => this : () => typeof globalThis +>this : typeof globalThis diff --git a/tests/baselines/reference/collisionThisExpressionAndFunctionInGlobal.symbols b/tests/baselines/reference/collisionThisExpressionAndFunctionInGlobal.symbols index a5d171dbe94..5461d86a0fc 100644 --- a/tests/baselines/reference/collisionThisExpressionAndFunctionInGlobal.symbols +++ b/tests/baselines/reference/collisionThisExpressionAndFunctionInGlobal.symbols @@ -6,4 +6,5 @@ function _this() { //Error } var f = () => this; >f : Symbol(f, Decl(collisionThisExpressionAndFunctionInGlobal.ts, 3, 3)) +>this : Symbol(globalThis) diff --git a/tests/baselines/reference/collisionThisExpressionAndFunctionInGlobal.types b/tests/baselines/reference/collisionThisExpressionAndFunctionInGlobal.types index bb0e11172cc..d3e4b57f58c 100644 --- a/tests/baselines/reference/collisionThisExpressionAndFunctionInGlobal.types +++ b/tests/baselines/reference/collisionThisExpressionAndFunctionInGlobal.types @@ -6,7 +6,7 @@ function _this() { //Error >10 : 10 } var f = () => this; ->f : () => any ->() => this : () => any ->this : any +>f : () => typeof globalThis +>() => this : () => typeof globalThis +>this : typeof globalThis diff --git a/tests/baselines/reference/collisionThisExpressionAndLocalVarInLambda.symbols b/tests/baselines/reference/collisionThisExpressionAndLocalVarInLambda.symbols index 2105baf09a2..79bfda70d28 100644 --- a/tests/baselines/reference/collisionThisExpressionAndLocalVarInLambda.symbols +++ b/tests/baselines/reference/collisionThisExpressionAndLocalVarInLambda.symbols @@ -15,6 +15,7 @@ var x = { return callback(this); >callback : Symbol(callback, Decl(collisionThisExpressionAndLocalVarInLambda.ts, 3, 14)) +>this : Symbol(globalThis) } } alert(x.doStuff(x => alert(x))); diff --git a/tests/baselines/reference/collisionThisExpressionAndLocalVarInLambda.types b/tests/baselines/reference/collisionThisExpressionAndLocalVarInLambda.types index cbc625b36e1..d1f051e339c 100644 --- a/tests/baselines/reference/collisionThisExpressionAndLocalVarInLambda.types +++ b/tests/baselines/reference/collisionThisExpressionAndLocalVarInLambda.types @@ -20,7 +20,7 @@ var x = { return callback(this); >callback(this) : any >callback : any ->this : any +>this : typeof globalThis } } alert(x.doStuff(x => alert(x))); diff --git a/tests/baselines/reference/collisionThisExpressionAndModuleInGlobal.symbols b/tests/baselines/reference/collisionThisExpressionAndModuleInGlobal.symbols index 8dcb9dca6d2..8cd392ac268 100644 --- a/tests/baselines/reference/collisionThisExpressionAndModuleInGlobal.symbols +++ b/tests/baselines/reference/collisionThisExpressionAndModuleInGlobal.symbols @@ -8,4 +8,5 @@ module _this { //Error } var f = () => this; >f : Symbol(f, Decl(collisionThisExpressionAndModuleInGlobal.ts, 4, 3)) +>this : Symbol(globalThis) diff --git a/tests/baselines/reference/collisionThisExpressionAndModuleInGlobal.types b/tests/baselines/reference/collisionThisExpressionAndModuleInGlobal.types index b950cda2d10..ffa6fcb1a02 100644 --- a/tests/baselines/reference/collisionThisExpressionAndModuleInGlobal.types +++ b/tests/baselines/reference/collisionThisExpressionAndModuleInGlobal.types @@ -7,7 +7,7 @@ module _this { //Error } } var f = () => this; ->f : () => any ->() => this : () => any ->this : any +>f : () => typeof globalThis +>() => this : () => typeof globalThis +>this : typeof globalThis diff --git a/tests/baselines/reference/collisionThisExpressionAndVarInGlobal.symbols b/tests/baselines/reference/collisionThisExpressionAndVarInGlobal.symbols index 5895e29b2c2..9554f0013f9 100644 --- a/tests/baselines/reference/collisionThisExpressionAndVarInGlobal.symbols +++ b/tests/baselines/reference/collisionThisExpressionAndVarInGlobal.symbols @@ -4,4 +4,5 @@ var _this = 1; var f = () => this; >f : Symbol(f, Decl(collisionThisExpressionAndVarInGlobal.ts, 1, 3)) +>this : Symbol(globalThis) diff --git a/tests/baselines/reference/collisionThisExpressionAndVarInGlobal.types b/tests/baselines/reference/collisionThisExpressionAndVarInGlobal.types index dd12ea63502..a82334edc49 100644 --- a/tests/baselines/reference/collisionThisExpressionAndVarInGlobal.types +++ b/tests/baselines/reference/collisionThisExpressionAndVarInGlobal.types @@ -4,7 +4,7 @@ var _this = 1; >1 : 1 var f = () => this; ->f : () => any ->() => this : () => any ->this : any +>f : () => typeof globalThis +>() => this : () => typeof globalThis +>this : typeof globalThis diff --git a/tests/baselines/reference/commentsInterface.symbols b/tests/baselines/reference/commentsInterface.symbols index 6e3a9e27978..d98dae0c893 100644 --- a/tests/baselines/reference/commentsInterface.symbols +++ b/tests/baselines/reference/commentsInterface.symbols @@ -187,19 +187,25 @@ i3_i = { l: this.f, >l : Symbol(l, Decl(commentsInterface.ts, 56, 56)) +>this : Symbol(globalThis) /** own x*/ x: this.f(10), >x : Symbol(x, Decl(commentsInterface.ts, 57, 14)) +>this : Symbol(globalThis) nc_x: this.l(this.x), >nc_x : Symbol(nc_x, Decl(commentsInterface.ts, 59, 18)) +>this : Symbol(globalThis) +>this : Symbol(globalThis) nc_f: this.f, >nc_f : Symbol(nc_f, Decl(commentsInterface.ts, 60, 25)) +>this : Symbol(globalThis) nc_l: this.l >nc_l : Symbol(nc_l, Decl(commentsInterface.ts, 61, 17)) +>this : Symbol(globalThis) }; i3_i.f(10); diff --git a/tests/baselines/reference/commentsInterface.types b/tests/baselines/reference/commentsInterface.types index 65f1f5f4a38..97169b771d3 100644 --- a/tests/baselines/reference/commentsInterface.types +++ b/tests/baselines/reference/commentsInterface.types @@ -198,7 +198,7 @@ i3_i = { l: this.f, >l : any >this.f : any ->this : any +>this : typeof globalThis >f : any /** own x*/ @@ -206,7 +206,7 @@ i3_i = { >x : any >this.f(10) : any >this.f : any ->this : any +>this : typeof globalThis >f : any >10 : 10 @@ -214,22 +214,22 @@ i3_i = { >nc_x : any >this.l(this.x) : any >this.l : any ->this : any +>this : typeof globalThis >l : any >this.x : any ->this : any +>this : typeof globalThis >x : any nc_f: this.f, >nc_f : any >this.f : any ->this : any +>this : typeof globalThis >f : any nc_l: this.l >nc_l : any >this.l : any ->this : any +>this : typeof globalThis >l : any }; diff --git a/tests/baselines/reference/compoundAssignmentLHSIsValue.errors.txt b/tests/baselines/reference/compoundAssignmentLHSIsValue.errors.txt index 8a133148007..2c22361bfd6 100644 --- a/tests/baselines/reference/compoundAssignmentLHSIsValue.errors.txt +++ b/tests/baselines/reference/compoundAssignmentLHSIsValue.errors.txt @@ -6,7 +6,7 @@ tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsVa tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(16,9): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(21,5): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(22,5): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(25,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(25,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(26,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(30,1): error TS2539: Cannot assign to 'M' because it is not a variable. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(31,1): error TS2539: Cannot assign to 'M' because it is not a variable. @@ -45,7 +45,7 @@ tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsVa tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(88,11): error TS1005: ';' expected. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(91,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(92,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. -tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(95,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(95,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(96,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(97,2): error TS2539: Cannot assign to 'M' because it is not a variable. tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts(98,2): error TS2539: Cannot assign to 'M' because it is not a variable. @@ -119,7 +119,7 @@ tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsVa this *= value; ~~~~ -!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. this += value; ~~~~ !!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. @@ -267,7 +267,7 @@ tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsVa // parentheses, the containted expression is value (this) *= value; ~~~~~~ -!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. (this) += value; ~~~~~~ !!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. diff --git a/tests/baselines/reference/compoundAssignmentLHSIsValue.symbols b/tests/baselines/reference/compoundAssignmentLHSIsValue.symbols index 790c05ed9a1..891127c32cc 100644 --- a/tests/baselines/reference/compoundAssignmentLHSIsValue.symbols +++ b/tests/baselines/reference/compoundAssignmentLHSIsValue.symbols @@ -51,9 +51,11 @@ function foo() { } this *= value; +>this : Symbol(globalThis) >value : Symbol(value, Decl(compoundAssignmentLHSIsValue.ts, 1, 3)) this += value; +>this : Symbol(globalThis) >value : Symbol(value, Decl(compoundAssignmentLHSIsValue.ts, 1, 3)) // identifiers: module, class, enum, function @@ -216,9 +218,11 @@ foo() += value; // parentheses, the containted expression is value (this) *= value; +>this : Symbol(globalThis) >value : Symbol(value, Decl(compoundAssignmentLHSIsValue.ts, 1, 3)) (this) += value; +>this : Symbol(globalThis) >value : Symbol(value, Decl(compoundAssignmentLHSIsValue.ts, 1, 3)) (M) *= value; diff --git a/tests/baselines/reference/compoundAssignmentLHSIsValue.types b/tests/baselines/reference/compoundAssignmentLHSIsValue.types index 7736256f973..5aafaa2647c 100644 --- a/tests/baselines/reference/compoundAssignmentLHSIsValue.types +++ b/tests/baselines/reference/compoundAssignmentLHSIsValue.types @@ -62,12 +62,12 @@ function foo() { this *= value; >this *= value : number ->this : any +>this : typeof globalThis >value : any this += value; >this += value : any ->this : any +>this : typeof globalThis >value : any // identifiers: module, class, enum, function @@ -300,14 +300,14 @@ foo() += value; // parentheses, the containted expression is value (this) *= value; >(this) *= value : number ->(this) : any ->this : any +>(this) : typeof globalThis +>this : typeof globalThis >value : any (this) += value; >(this) += value : any ->(this) : any ->this : any +>(this) : typeof globalThis +>this : typeof globalThis >value : any (M) *= value; diff --git a/tests/baselines/reference/compoundExponentiationAssignmentLHSIsValue.errors.txt b/tests/baselines/reference/compoundExponentiationAssignmentLHSIsValue.errors.txt index e3c9918aa4b..37e9ca6be1d 100644 --- a/tests/baselines/reference/compoundExponentiationAssignmentLHSIsValue.errors.txt +++ b/tests/baselines/reference/compoundExponentiationAssignmentLHSIsValue.errors.txt @@ -2,7 +2,7 @@ tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignm tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(10,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(13,9): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(18,5): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(21,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(21,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(25,1): error TS2539: Cannot assign to 'M' because it is not a variable. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(27,1): error TS2539: Cannot assign to 'C' because it is not a variable. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(30,1): error TS2539: Cannot assign to 'E' because it is not a variable. @@ -22,7 +22,7 @@ tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignm tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(65,21): error TS1128: Declaration or statement expected. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(66,11): error TS1005: ';' expected. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(69,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. -tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(72,1): error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(72,1): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(73,2): error TS2539: Cannot assign to 'M' because it is not a variable. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(74,2): error TS2539: Cannot assign to 'C' because it is not a variable. tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignmentLHSIsValue.ts(75,2): error TS2539: Cannot assign to 'E' because it is not a variable. @@ -70,7 +70,7 @@ tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignm this **= value; ~~~~ -!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. // identifiers: module, class, enum, function module M { export var a; } @@ -161,7 +161,7 @@ tests/cases/conformance/es7/exponentiationOperator/compoundExponentiationAssignm // parentheses, the containted expression is value (this) **= value; ~~~~~~ -!!! error TS2364: The left-hand side of an assignment expression must be a variable or a property access. +!!! error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. (M) **= value; ~ !!! error TS2539: Cannot assign to 'M' because it is not a variable. diff --git a/tests/baselines/reference/compoundExponentiationAssignmentLHSIsValue.symbols b/tests/baselines/reference/compoundExponentiationAssignmentLHSIsValue.symbols index 7e85139b7a8..5596f648979 100644 --- a/tests/baselines/reference/compoundExponentiationAssignmentLHSIsValue.symbols +++ b/tests/baselines/reference/compoundExponentiationAssignmentLHSIsValue.symbols @@ -36,6 +36,7 @@ function foo() { } this **= value; +>this : Symbol(globalThis) >value : Symbol(value, Decl(compoundExponentiationAssignmentLHSIsValue.ts, 1, 3)) // identifiers: module, class, enum, function @@ -135,6 +136,7 @@ foo() **= value; // parentheses, the containted expression is value (this) **= value; +>this : Symbol(globalThis) >value : Symbol(value, Decl(compoundExponentiationAssignmentLHSIsValue.ts, 1, 3)) (M) **= value; diff --git a/tests/baselines/reference/compoundExponentiationAssignmentLHSIsValue.types b/tests/baselines/reference/compoundExponentiationAssignmentLHSIsValue.types index 982b6b2bdee..58ec77add86 100644 --- a/tests/baselines/reference/compoundExponentiationAssignmentLHSIsValue.types +++ b/tests/baselines/reference/compoundExponentiationAssignmentLHSIsValue.types @@ -42,7 +42,7 @@ function foo() { this **= value; >this **= value : number ->this : any +>this : typeof globalThis >value : any // identifiers: module, class, enum, function @@ -178,8 +178,8 @@ foo() **= value; // parentheses, the containted expression is value (this) **= value; >(this) **= value : number ->(this) : any ->this : any +>(this) : typeof globalThis +>this : typeof globalThis >value : any (M) **= value; diff --git a/tests/baselines/reference/computedPropertyNames20_ES5.symbols b/tests/baselines/reference/computedPropertyNames20_ES5.symbols index 2b249fd8f95..3ac422d6e73 100644 --- a/tests/baselines/reference/computedPropertyNames20_ES5.symbols +++ b/tests/baselines/reference/computedPropertyNames20_ES5.symbols @@ -4,4 +4,5 @@ var obj = { [this.bar]: 0 >[this.bar] : Symbol([this.bar], Decl(computedPropertyNames20_ES5.ts, 0, 11)) +>this : Symbol(globalThis) } diff --git a/tests/baselines/reference/computedPropertyNames20_ES5.types b/tests/baselines/reference/computedPropertyNames20_ES5.types index cc0614b3d0b..7a958724811 100644 --- a/tests/baselines/reference/computedPropertyNames20_ES5.types +++ b/tests/baselines/reference/computedPropertyNames20_ES5.types @@ -6,7 +6,7 @@ var obj = { [this.bar]: 0 >[this.bar] : number >this.bar : any ->this : any +>this : typeof globalThis >bar : any >0 : 0 } diff --git a/tests/baselines/reference/computedPropertyNames20_ES6.symbols b/tests/baselines/reference/computedPropertyNames20_ES6.symbols index ffd5645ccd6..62c934426fd 100644 --- a/tests/baselines/reference/computedPropertyNames20_ES6.symbols +++ b/tests/baselines/reference/computedPropertyNames20_ES6.symbols @@ -4,4 +4,5 @@ var obj = { [this.bar]: 0 >[this.bar] : Symbol([this.bar], Decl(computedPropertyNames20_ES6.ts, 0, 11)) +>this : Symbol(globalThis) } diff --git a/tests/baselines/reference/computedPropertyNames20_ES6.types b/tests/baselines/reference/computedPropertyNames20_ES6.types index 5ffc037860e..516559e3e3e 100644 --- a/tests/baselines/reference/computedPropertyNames20_ES6.types +++ b/tests/baselines/reference/computedPropertyNames20_ES6.types @@ -6,7 +6,7 @@ var obj = { [this.bar]: 0 >[this.bar] : number >this.bar : any ->this : any +>this : typeof globalThis >bar : any >0 : 0 } diff --git a/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.symbols b/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.symbols index c5f1afffb2f..f7e719e39d3 100644 --- a/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.symbols +++ b/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.symbols @@ -579,6 +579,7 @@ module TypeScriptAllInOne { } public method2() { return 2 * this.method1(2); +>this : Symbol(globalThis) } } diff --git a/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.types b/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.types index c4428efcd4d..affae0f3108 100644 --- a/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.types +++ b/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.types @@ -869,7 +869,7 @@ module TypeScriptAllInOne { >2 : 2 >this.method1(2) : any >this.method1 : any ->this : any +>this : typeof globalThis >method1 : any >2 : 2 } diff --git a/tests/baselines/reference/emitArrowFunctionThisCapturing.errors.txt b/tests/baselines/reference/emitArrowFunctionThisCapturing.errors.txt new file mode 100644 index 00000000000..2030b47b3ec --- /dev/null +++ b/tests/baselines/reference/emitArrowFunctionThisCapturing.errors.txt @@ -0,0 +1,20 @@ +tests/cases/conformance/es6/arrowFunction/emitArrowFunctionThisCapturing.ts(6,10): error TS2540: Cannot assign to 'name' because it is a read-only property. + + +==== tests/cases/conformance/es6/arrowFunction/emitArrowFunctionThisCapturing.ts (1 errors) ==== + var f1 = () => { + this.age = 10 + }; + + var f2 = (x: string) => { + this.name = x + ~~~~ +!!! error TS2540: Cannot assign to 'name' because it is a read-only property. + } + + function foo(func: () => boolean) { } + foo(() => { + this.age = 100; + return true; + }); + \ No newline at end of file diff --git a/tests/baselines/reference/emitArrowFunctionThisCapturing.symbols b/tests/baselines/reference/emitArrowFunctionThisCapturing.symbols index ad62a0df5be..e130eafd770 100644 --- a/tests/baselines/reference/emitArrowFunctionThisCapturing.symbols +++ b/tests/baselines/reference/emitArrowFunctionThisCapturing.symbols @@ -3,6 +3,8 @@ var f1 = () => { >f1 : Symbol(f1, Decl(emitArrowFunctionThisCapturing.ts, 0, 3)) this.age = 10 +>this : Symbol(globalThis) + }; var f2 = (x: string) => { @@ -10,6 +12,9 @@ var f2 = (x: string) => { >x : Symbol(x, Decl(emitArrowFunctionThisCapturing.ts, 4, 10)) this.name = x +>this.name : Symbol(name, Decl(lib.dom.d.ts, --, --)) +>this : Symbol(globalThis) +>name : Symbol(name, Decl(lib.dom.d.ts, --, --)) >x : Symbol(x, Decl(emitArrowFunctionThisCapturing.ts, 4, 10)) } @@ -21,6 +26,8 @@ foo(() => { >foo : Symbol(foo, Decl(emitArrowFunctionThisCapturing.ts, 6, 1)) this.age = 100; +>this : Symbol(globalThis) + return true; }); diff --git a/tests/baselines/reference/emitArrowFunctionThisCapturing.types b/tests/baselines/reference/emitArrowFunctionThisCapturing.types index 0ef27791d17..8edaa3141da 100644 --- a/tests/baselines/reference/emitArrowFunctionThisCapturing.types +++ b/tests/baselines/reference/emitArrowFunctionThisCapturing.types @@ -6,7 +6,7 @@ var f1 = () => { this.age = 10 >this.age = 10 : 10 >this.age : any ->this : any +>this : typeof globalThis >age : any >10 : 10 @@ -20,7 +20,7 @@ var f2 = (x: string) => { this.name = x >this.name = x : string >this.name : any ->this : any +>this : typeof globalThis >name : any >x : string } @@ -37,7 +37,7 @@ foo(() => { this.age = 100; >this.age = 100 : 100 >this.age : any ->this : any +>this : typeof globalThis >age : any >100 : 100 diff --git a/tests/baselines/reference/emitArrowFunctionThisCapturingES6.errors.txt b/tests/baselines/reference/emitArrowFunctionThisCapturingES6.errors.txt new file mode 100644 index 00000000000..fb644a4127e --- /dev/null +++ b/tests/baselines/reference/emitArrowFunctionThisCapturingES6.errors.txt @@ -0,0 +1,20 @@ +tests/cases/conformance/es6/arrowFunction/emitArrowFunctionThisCapturingES6.ts(6,10): error TS2540: Cannot assign to 'name' because it is a read-only property. + + +==== tests/cases/conformance/es6/arrowFunction/emitArrowFunctionThisCapturingES6.ts (1 errors) ==== + var f1 = () => { + this.age = 10 + }; + + var f2 = (x: string) => { + this.name = x + ~~~~ +!!! error TS2540: Cannot assign to 'name' because it is a read-only property. + } + + function foo(func: () => boolean){ } + foo(() => { + this.age = 100; + return true; + }); + \ No newline at end of file diff --git a/tests/baselines/reference/emitArrowFunctionThisCapturingES6.symbols b/tests/baselines/reference/emitArrowFunctionThisCapturingES6.symbols index 0e8855dd680..d370a207de6 100644 --- a/tests/baselines/reference/emitArrowFunctionThisCapturingES6.symbols +++ b/tests/baselines/reference/emitArrowFunctionThisCapturingES6.symbols @@ -3,6 +3,8 @@ var f1 = () => { >f1 : Symbol(f1, Decl(emitArrowFunctionThisCapturingES6.ts, 0, 3)) this.age = 10 +>this : Symbol(globalThis) + }; var f2 = (x: string) => { @@ -10,6 +12,9 @@ var f2 = (x: string) => { >x : Symbol(x, Decl(emitArrowFunctionThisCapturingES6.ts, 4, 10)) this.name = x +>this.name : Symbol(name, Decl(lib.dom.d.ts, --, --)) +>this : Symbol(globalThis) +>name : Symbol(name, Decl(lib.dom.d.ts, --, --)) >x : Symbol(x, Decl(emitArrowFunctionThisCapturingES6.ts, 4, 10)) } @@ -21,6 +26,8 @@ foo(() => { >foo : Symbol(foo, Decl(emitArrowFunctionThisCapturingES6.ts, 6, 1)) this.age = 100; +>this : Symbol(globalThis) + return true; }); diff --git a/tests/baselines/reference/emitArrowFunctionThisCapturingES6.types b/tests/baselines/reference/emitArrowFunctionThisCapturingES6.types index 3c20bfd195c..c57317ec5bf 100644 --- a/tests/baselines/reference/emitArrowFunctionThisCapturingES6.types +++ b/tests/baselines/reference/emitArrowFunctionThisCapturingES6.types @@ -6,7 +6,7 @@ var f1 = () => { this.age = 10 >this.age = 10 : 10 >this.age : any ->this : any +>this : typeof globalThis >age : any >10 : 10 @@ -20,7 +20,7 @@ var f2 = (x: string) => { this.name = x >this.name = x : string >this.name : any ->this : any +>this : typeof globalThis >name : any >x : string } @@ -37,7 +37,7 @@ foo(() => { this.age = 100; >this.age = 100 : 100 >this.age : any ->this : any +>this : typeof globalThis >age : any >100 : 100 diff --git a/tests/baselines/reference/emitCapturingThisInTupleDestructuring1.symbols b/tests/baselines/reference/emitCapturingThisInTupleDestructuring1.symbols index 6bd13ccfd47..bfef6d5b3e3 100644 --- a/tests/baselines/reference/emitCapturingThisInTupleDestructuring1.symbols +++ b/tests/baselines/reference/emitCapturingThisInTupleDestructuring1.symbols @@ -8,6 +8,9 @@ wrapper((array: [any]) => { >array : Symbol(array, Decl(emitCapturingThisInTupleDestructuring1.ts, 1, 9)) [this.test, this.test1, this.test2] = array; // even though there is a compiler error, we should still emit lexical capture for "this" +>this : Symbol(globalThis) +>this : Symbol(globalThis) +>this : Symbol(globalThis) >array : Symbol(array, Decl(emitCapturingThisInTupleDestructuring1.ts, 1, 9)) }); diff --git a/tests/baselines/reference/emitCapturingThisInTupleDestructuring1.types b/tests/baselines/reference/emitCapturingThisInTupleDestructuring1.types index 7e9f03780ca..9cd06b6b560 100644 --- a/tests/baselines/reference/emitCapturingThisInTupleDestructuring1.types +++ b/tests/baselines/reference/emitCapturingThisInTupleDestructuring1.types @@ -13,13 +13,13 @@ wrapper((array: [any]) => { >[this.test, this.test1, this.test2] = array : [any] >[this.test, this.test1, this.test2] : [any, any, any] >this.test : any ->this : any +>this : typeof globalThis >test : any >this.test1 : any ->this : any +>this : typeof globalThis >test1 : any >this.test2 : any ->this : any +>this : typeof globalThis >test2 : any >array : [any] diff --git a/tests/baselines/reference/globalThisCapture.symbols b/tests/baselines/reference/globalThisCapture.symbols index bfb7bf147c0..9ece286c98f 100644 --- a/tests/baselines/reference/globalThisCapture.symbols +++ b/tests/baselines/reference/globalThisCapture.symbols @@ -1,6 +1,9 @@ === tests/cases/compiler/globalThisCapture.ts === // Add a lambda to ensure global 'this' capture is triggered (()=>this.window); +>this.window : Symbol(window, Decl(lib.dom.d.ts, --, --)) +>this : Symbol(globalThis) +>window : Symbol(window, Decl(lib.dom.d.ts, --, --)) var parts = []; >parts : Symbol(parts, Decl(globalThisCapture.ts, 3, 3)) diff --git a/tests/baselines/reference/globalThisCapture.types b/tests/baselines/reference/globalThisCapture.types index 063100ff78e..43a06138228 100644 --- a/tests/baselines/reference/globalThisCapture.types +++ b/tests/baselines/reference/globalThisCapture.types @@ -1,11 +1,11 @@ === tests/cases/compiler/globalThisCapture.ts === // Add a lambda to ensure global 'this' capture is triggered (()=>this.window); ->(()=>this.window) : () => any ->()=>this.window : () => any ->this.window : any ->this : any ->window : any +>(()=>this.window) : () => Window +>()=>this.window : () => Window +>this.window : Window +>this : typeof globalThis +>window : Window var parts = []; >parts : any[] diff --git a/tests/baselines/reference/globalThisPropertyAssignment.errors.txt b/tests/baselines/reference/globalThisPropertyAssignment.errors.txt new file mode 100644 index 00000000000..a02824415ae --- /dev/null +++ b/tests/baselines/reference/globalThisPropertyAssignment.errors.txt @@ -0,0 +1,13 @@ +tests/cases/conformance/es2019/globalThisPropertyAssignment.js(4,8): error TS2339: Property 'z' does not exist on type 'Window'. + + +==== tests/cases/conformance/es2019/globalThisPropertyAssignment.js (1 errors) ==== + this.x = 1 + var y = 2 + // should work in JS + window.z = 3 + ~ +!!! error TS2339: Property 'z' does not exist on type 'Window'. + // should work in JS (even though it's a secondary declaration) + globalThis.alpha = 4 + \ No newline at end of file diff --git a/tests/baselines/reference/globalThisPropertyAssignment.symbols b/tests/baselines/reference/globalThisPropertyAssignment.symbols new file mode 100644 index 00000000000..1ae4dd5af63 --- /dev/null +++ b/tests/baselines/reference/globalThisPropertyAssignment.symbols @@ -0,0 +1,19 @@ +=== tests/cases/conformance/es2019/globalThisPropertyAssignment.js === +this.x = 1 +>this.x : Symbol(x, Decl(globalThisPropertyAssignment.js, 0, 0)) +>this : Symbol(globalThis) +>x : Symbol(x, Decl(globalThisPropertyAssignment.js, 0, 0)) + +var y = 2 +>y : Symbol(y, Decl(globalThisPropertyAssignment.js, 1, 3)) + +// should work in JS +window.z = 3 +>window : Symbol(window, Decl(lib.dom.d.ts, --, --), Decl(globalThisPropertyAssignment.js, 1, 9)) + +// should work in JS (even though it's a secondary declaration) +globalThis.alpha = 4 +>globalThis.alpha : Symbol(alpha, Decl(globalThisPropertyAssignment.js, 3, 12)) +>globalThis : Symbol(globalThis) +>alpha : Symbol(alpha, Decl(globalThisPropertyAssignment.js, 3, 12)) + diff --git a/tests/baselines/reference/globalThisPropertyAssignment.types b/tests/baselines/reference/globalThisPropertyAssignment.types new file mode 100644 index 00000000000..6be55e136b0 --- /dev/null +++ b/tests/baselines/reference/globalThisPropertyAssignment.types @@ -0,0 +1,28 @@ +=== tests/cases/conformance/es2019/globalThisPropertyAssignment.js === +this.x = 1 +>this.x = 1 : 1 +>this.x : number +>this : typeof globalThis +>x : number +>1 : 1 + +var y = 2 +>y : number +>2 : 2 + +// should work in JS +window.z = 3 +>window.z = 3 : 3 +>window.z : any +>window : Window +>z : any +>3 : 3 + +// should work in JS (even though it's a secondary declaration) +globalThis.alpha = 4 +>globalThis.alpha = 4 : 4 +>globalThis.alpha : number +>globalThis : typeof globalThis +>alpha : number +>4 : 4 + diff --git a/tests/baselines/reference/globalThisReadonlyProperties.errors.txt b/tests/baselines/reference/globalThisReadonlyProperties.errors.txt new file mode 100644 index 00000000000..925cf90a10c --- /dev/null +++ b/tests/baselines/reference/globalThisReadonlyProperties.errors.txt @@ -0,0 +1,15 @@ +tests/cases/conformance/es2019/globalThisReadonlyProperties.ts(1,12): error TS2540: Cannot assign to 'globalThis' because it is a read-only property. +tests/cases/conformance/es2019/globalThisReadonlyProperties.ts(5,12): error TS2540: Cannot assign to 'y' because it is a read-only property. + + +==== tests/cases/conformance/es2019/globalThisReadonlyProperties.ts (2 errors) ==== + globalThis.globalThis = 1 as any // should error + ~~~~~~~~~~ +!!! error TS2540: Cannot assign to 'globalThis' because it is a read-only property. + var x = 1 + const y = 2 + globalThis.x = 3 + globalThis.y = 4 // should error + ~ +!!! error TS2540: Cannot assign to 'y' because it is a read-only property. + \ No newline at end of file diff --git a/tests/baselines/reference/globalThisReadonlyProperties.js b/tests/baselines/reference/globalThisReadonlyProperties.js new file mode 100644 index 00000000000..3012608a125 --- /dev/null +++ b/tests/baselines/reference/globalThisReadonlyProperties.js @@ -0,0 +1,14 @@ +//// [globalThisReadonlyProperties.ts] +globalThis.globalThis = 1 as any // should error +var x = 1 +const y = 2 +globalThis.x = 3 +globalThis.y = 4 // should error + + +//// [globalThisReadonlyProperties.js] +globalThis.globalThis = 1; // should error +var x = 1; +var y = 2; +globalThis.x = 3; +globalThis.y = 4; // should error diff --git a/tests/baselines/reference/globalThisReadonlyProperties.symbols b/tests/baselines/reference/globalThisReadonlyProperties.symbols new file mode 100644 index 00000000000..df59ee45ca3 --- /dev/null +++ b/tests/baselines/reference/globalThisReadonlyProperties.symbols @@ -0,0 +1,22 @@ +=== tests/cases/conformance/es2019/globalThisReadonlyProperties.ts === +globalThis.globalThis = 1 as any // should error +>globalThis.globalThis : Symbol(globalThis) +>globalThis : Symbol(globalThis) +>globalThis : Symbol(globalThis) + +var x = 1 +>x : Symbol(x, Decl(globalThisReadonlyProperties.ts, 1, 3)) + +const y = 2 +>y : Symbol(y, Decl(globalThisReadonlyProperties.ts, 2, 5)) + +globalThis.x = 3 +>globalThis.x : Symbol(x, Decl(globalThisReadonlyProperties.ts, 1, 3)) +>globalThis : Symbol(globalThis) +>x : Symbol(x, Decl(globalThisReadonlyProperties.ts, 1, 3)) + +globalThis.y = 4 // should error +>globalThis.y : Symbol(y, Decl(globalThisReadonlyProperties.ts, 2, 5)) +>globalThis : Symbol(globalThis) +>y : Symbol(y, Decl(globalThisReadonlyProperties.ts, 2, 5)) + diff --git a/tests/baselines/reference/globalThisReadonlyProperties.types b/tests/baselines/reference/globalThisReadonlyProperties.types new file mode 100644 index 00000000000..05b3d7c84e8 --- /dev/null +++ b/tests/baselines/reference/globalThisReadonlyProperties.types @@ -0,0 +1,31 @@ +=== tests/cases/conformance/es2019/globalThisReadonlyProperties.ts === +globalThis.globalThis = 1 as any // should error +>globalThis.globalThis = 1 as any : any +>globalThis.globalThis : any +>globalThis : typeof globalThis +>globalThis : any +>1 as any : any +>1 : 1 + +var x = 1 +>x : number +>1 : 1 + +const y = 2 +>y : 2 +>2 : 2 + +globalThis.x = 3 +>globalThis.x = 3 : 3 +>globalThis.x : number +>globalThis : typeof globalThis +>x : number +>3 : 3 + +globalThis.y = 4 // should error +>globalThis.y = 4 : 4 +>globalThis.y : any +>globalThis : typeof globalThis +>y : any +>4 : 4 + diff --git a/tests/baselines/reference/globalThisTypeIndexAccess.js b/tests/baselines/reference/globalThisTypeIndexAccess.js new file mode 100644 index 00000000000..aef5c97ed9a --- /dev/null +++ b/tests/baselines/reference/globalThisTypeIndexAccess.js @@ -0,0 +1,5 @@ +//// [globalThisTypeIndexAccess.ts] +declare const w_e: (typeof globalThis)["globalThis"] + + +//// [globalThisTypeIndexAccess.js] diff --git a/tests/baselines/reference/globalThisTypeIndexAccess.symbols b/tests/baselines/reference/globalThisTypeIndexAccess.symbols new file mode 100644 index 00000000000..460867fb1f1 --- /dev/null +++ b/tests/baselines/reference/globalThisTypeIndexAccess.symbols @@ -0,0 +1,5 @@ +=== tests/cases/conformance/es2019/globalThisTypeIndexAccess.ts === +declare const w_e: (typeof globalThis)["globalThis"] +>w_e : Symbol(w_e, Decl(globalThisTypeIndexAccess.ts, 0, 13)) +>globalThis : Symbol(globalThis) + diff --git a/tests/baselines/reference/globalThisTypeIndexAccess.types b/tests/baselines/reference/globalThisTypeIndexAccess.types new file mode 100644 index 00000000000..c290b744071 --- /dev/null +++ b/tests/baselines/reference/globalThisTypeIndexAccess.types @@ -0,0 +1,5 @@ +=== tests/cases/conformance/es2019/globalThisTypeIndexAccess.ts === +declare const w_e: (typeof globalThis)["globalThis"] +>w_e : typeof globalThis +>globalThis : typeof globalThis + diff --git a/tests/baselines/reference/globalThisUnknown.errors.txt b/tests/baselines/reference/globalThisUnknown.errors.txt new file mode 100644 index 00000000000..fc9a8485b64 --- /dev/null +++ b/tests/baselines/reference/globalThisUnknown.errors.txt @@ -0,0 +1,20 @@ +tests/cases/conformance/es2019/globalThisUnknown.ts(4,5): error TS2339: Property 'hi' does not exist on type 'Window & typeof globalThis'. + + +==== tests/cases/conformance/es2019/globalThisUnknown.ts (1 errors) ==== + declare let win: Window & typeof globalThis; + + // this access should be an error + win.hi + ~~ +!!! error TS2339: Property 'hi' does not exist on type 'Window & typeof globalThis'. + // these two should be fine, with type any + this.hi + globalThis.hi + + // element access is always ok without noImplicitAny + win['hi'] + this['hi'] + globalThis['hi'] + + \ No newline at end of file diff --git a/tests/baselines/reference/globalThisUnknown.js b/tests/baselines/reference/globalThisUnknown.js new file mode 100644 index 00000000000..9763100c129 --- /dev/null +++ b/tests/baselines/reference/globalThisUnknown.js @@ -0,0 +1,26 @@ +//// [globalThisUnknown.ts] +declare let win: Window & typeof globalThis; + +// this access should be an error +win.hi +// these two should be fine, with type any +this.hi +globalThis.hi + +// element access is always ok without noImplicitAny +win['hi'] +this['hi'] +globalThis['hi'] + + + +//// [globalThisUnknown.js] +// this access should be an error +win.hi; +// these two should be fine, with type any +this.hi; +globalThis.hi; +// element access is always ok without noImplicitAny +win['hi']; +this['hi']; +globalThis['hi']; diff --git a/tests/baselines/reference/globalThisUnknown.symbols b/tests/baselines/reference/globalThisUnknown.symbols new file mode 100644 index 00000000000..4f8437bf244 --- /dev/null +++ b/tests/baselines/reference/globalThisUnknown.symbols @@ -0,0 +1,28 @@ +=== tests/cases/conformance/es2019/globalThisUnknown.ts === +declare let win: Window & typeof globalThis; +>win : Symbol(win, Decl(globalThisUnknown.ts, 0, 11)) +>Window : Symbol(Window, Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --)) +>globalThis : Symbol(globalThis) + +// this access should be an error +win.hi +>win : Symbol(win, Decl(globalThisUnknown.ts, 0, 11)) + +// these two should be fine, with type any +this.hi +>this : Symbol(globalThis) + +globalThis.hi +>globalThis : Symbol(globalThis) + +// element access is always ok without noImplicitAny +win['hi'] +>win : Symbol(win, Decl(globalThisUnknown.ts, 0, 11)) + +this['hi'] +>this : Symbol(globalThis) + +globalThis['hi'] +>globalThis : Symbol(globalThis) + + diff --git a/tests/baselines/reference/globalThisUnknown.types b/tests/baselines/reference/globalThisUnknown.types new file mode 100644 index 00000000000..42ac606ec54 --- /dev/null +++ b/tests/baselines/reference/globalThisUnknown.types @@ -0,0 +1,39 @@ +=== tests/cases/conformance/es2019/globalThisUnknown.ts === +declare let win: Window & typeof globalThis; +>win : Window & typeof globalThis +>globalThis : typeof globalThis + +// this access should be an error +win.hi +>win.hi : any +>win : Window & typeof globalThis +>hi : any + +// these two should be fine, with type any +this.hi +>this.hi : any +>this : typeof globalThis +>hi : any + +globalThis.hi +>globalThis.hi : any +>globalThis : typeof globalThis +>hi : any + +// element access is always ok without noImplicitAny +win['hi'] +>win['hi'] : any +>win : Window & typeof globalThis +>'hi' : "hi" + +this['hi'] +>this['hi'] : any +>this : typeof globalThis +>'hi' : "hi" + +globalThis['hi'] +>globalThis['hi'] : any +>globalThis : typeof globalThis +>'hi' : "hi" + + diff --git a/tests/baselines/reference/globalThisUnknownNoImplicitAny.errors.txt b/tests/baselines/reference/globalThisUnknownNoImplicitAny.errors.txt new file mode 100644 index 00000000000..fc5e91de594 --- /dev/null +++ b/tests/baselines/reference/globalThisUnknownNoImplicitAny.errors.txt @@ -0,0 +1,32 @@ +tests/cases/conformance/es2019/globalThisUnknownNoImplicitAny.ts(4,5): error TS2339: Property 'hi' does not exist on type 'Window & typeof globalThis'. +tests/cases/conformance/es2019/globalThisUnknownNoImplicitAny.ts(5,6): error TS7017: Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature. +tests/cases/conformance/es2019/globalThisUnknownNoImplicitAny.ts(6,12): error TS7017: Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature. +tests/cases/conformance/es2019/globalThisUnknownNoImplicitAny.ts(8,1): error TS7017: Element implicitly has an 'any' type because type 'Window & typeof globalThis' has no index signature. +tests/cases/conformance/es2019/globalThisUnknownNoImplicitAny.ts(9,1): error TS7017: Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature. +tests/cases/conformance/es2019/globalThisUnknownNoImplicitAny.ts(10,1): error TS7017: Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature. + + +==== tests/cases/conformance/es2019/globalThisUnknownNoImplicitAny.ts (6 errors) ==== + declare let win: Window & typeof globalThis; + + // all accesses should be errors + win.hi + ~~ +!!! error TS2339: Property 'hi' does not exist on type 'Window & typeof globalThis'. + this.hi + ~~ +!!! error TS7017: Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature. + globalThis.hi + ~~ +!!! error TS7017: Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature. + + win['hi'] + ~~~~~~~~~ +!!! error TS7017: Element implicitly has an 'any' type because type 'Window & typeof globalThis' has no index signature. + this['hi'] + ~~~~~~~~~~ +!!! error TS7017: Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature. + globalThis['hi'] + ~~~~~~~~~~~~~~~~ +!!! error TS7017: Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature. + \ No newline at end of file diff --git a/tests/baselines/reference/globalThisUnknownNoImplicitAny.js b/tests/baselines/reference/globalThisUnknownNoImplicitAny.js new file mode 100644 index 00000000000..cc1952e0afc --- /dev/null +++ b/tests/baselines/reference/globalThisUnknownNoImplicitAny.js @@ -0,0 +1,21 @@ +//// [globalThisUnknownNoImplicitAny.ts] +declare let win: Window & typeof globalThis; + +// all accesses should be errors +win.hi +this.hi +globalThis.hi + +win['hi'] +this['hi'] +globalThis['hi'] + + +//// [globalThisUnknownNoImplicitAny.js] +// all accesses should be errors +win.hi; +this.hi; +globalThis.hi; +win['hi']; +this['hi']; +globalThis['hi']; diff --git a/tests/baselines/reference/globalThisUnknownNoImplicitAny.symbols b/tests/baselines/reference/globalThisUnknownNoImplicitAny.symbols new file mode 100644 index 00000000000..6aee6d6051c --- /dev/null +++ b/tests/baselines/reference/globalThisUnknownNoImplicitAny.symbols @@ -0,0 +1,25 @@ +=== tests/cases/conformance/es2019/globalThisUnknownNoImplicitAny.ts === +declare let win: Window & typeof globalThis; +>win : Symbol(win, Decl(globalThisUnknownNoImplicitAny.ts, 0, 11)) +>Window : Symbol(Window, Decl(lib.dom.d.ts, --, --), Decl(lib.dom.d.ts, --, --)) +>globalThis : Symbol(globalThis) + +// all accesses should be errors +win.hi +>win : Symbol(win, Decl(globalThisUnknownNoImplicitAny.ts, 0, 11)) + +this.hi +>this : Symbol(globalThis) + +globalThis.hi +>globalThis : Symbol(globalThis) + +win['hi'] +>win : Symbol(win, Decl(globalThisUnknownNoImplicitAny.ts, 0, 11)) + +this['hi'] +>this : Symbol(globalThis) + +globalThis['hi'] +>globalThis : Symbol(globalThis) + diff --git a/tests/baselines/reference/globalThisUnknownNoImplicitAny.types b/tests/baselines/reference/globalThisUnknownNoImplicitAny.types new file mode 100644 index 00000000000..19611a785b4 --- /dev/null +++ b/tests/baselines/reference/globalThisUnknownNoImplicitAny.types @@ -0,0 +1,36 @@ +=== tests/cases/conformance/es2019/globalThisUnknownNoImplicitAny.ts === +declare let win: Window & typeof globalThis; +>win : Window & typeof globalThis +>globalThis : typeof globalThis + +// all accesses should be errors +win.hi +>win.hi : any +>win : Window & typeof globalThis +>hi : any + +this.hi +>this.hi : any +>this : typeof globalThis +>hi : any + +globalThis.hi +>globalThis.hi : any +>globalThis : typeof globalThis +>hi : any + +win['hi'] +>win['hi'] : any +>win : Window & typeof globalThis +>'hi' : "hi" + +this['hi'] +>this['hi'] : any +>this : typeof globalThis +>'hi' : "hi" + +globalThis['hi'] +>globalThis['hi'] : any +>globalThis : typeof globalThis +>'hi' : "hi" + diff --git a/tests/baselines/reference/globalThisVarDeclaration.errors.txt b/tests/baselines/reference/globalThisVarDeclaration.errors.txt new file mode 100644 index 00000000000..daf2349c6b0 --- /dev/null +++ b/tests/baselines/reference/globalThisVarDeclaration.errors.txt @@ -0,0 +1,69 @@ +tests/cases/conformance/es2019/actual.ts(8,6): error TS2339: Property 'a' does not exist on type 'Window'. +tests/cases/conformance/es2019/actual.ts(9,6): error TS2339: Property 'b' does not exist on type 'Window'. +tests/cases/conformance/es2019/actual.ts(10,8): error TS2339: Property 'a' does not exist on type 'Window'. +tests/cases/conformance/es2019/actual.ts(11,8): error TS2339: Property 'b' does not exist on type 'Window'. +tests/cases/conformance/es2019/actual.ts(12,5): error TS2339: Property 'a' does not exist on type 'Window'. +tests/cases/conformance/es2019/actual.ts(13,5): error TS2339: Property 'b' does not exist on type 'Window'. +tests/cases/conformance/es2019/b.js(8,6): error TS2339: Property 'a' does not exist on type 'Window'. +tests/cases/conformance/es2019/b.js(9,6): error TS2339: Property 'b' does not exist on type 'Window'. +tests/cases/conformance/es2019/b.js(10,8): error TS2339: Property 'a' does not exist on type 'Window'. +tests/cases/conformance/es2019/b.js(11,8): error TS2339: Property 'b' does not exist on type 'Window'. +tests/cases/conformance/es2019/b.js(12,5): error TS2339: Property 'a' does not exist on type 'Window'. +tests/cases/conformance/es2019/b.js(13,5): error TS2339: Property 'b' does not exist on type 'Window'. + + +==== tests/cases/conformance/es2019/b.js (6 errors) ==== + var a = 10; + this.a; + this.b; + globalThis.a; + globalThis.b; + + // DOM access is not supported until the index signature is handled more strictly + self.a; + ~ +!!! error TS2339: Property 'a' does not exist on type 'Window'. + self.b; + ~ +!!! error TS2339: Property 'b' does not exist on type 'Window'. + window.a; + ~ +!!! error TS2339: Property 'a' does not exist on type 'Window'. + window.b; + ~ +!!! error TS2339: Property 'b' does not exist on type 'Window'. + top.a; + ~ +!!! error TS2339: Property 'a' does not exist on type 'Window'. + top.b; + ~ +!!! error TS2339: Property 'b' does not exist on type 'Window'. + +==== tests/cases/conformance/es2019/actual.ts (6 errors) ==== + var b = 10; + this.a; + this.b; + globalThis.a; + globalThis.b; + + // same here -- no DOM access to globalThis yet + self.a; + ~ +!!! error TS2339: Property 'a' does not exist on type 'Window'. + self.b; + ~ +!!! error TS2339: Property 'b' does not exist on type 'Window'. + window.a; + ~ +!!! error TS2339: Property 'a' does not exist on type 'Window'. + window.b; + ~ +!!! error TS2339: Property 'b' does not exist on type 'Window'. + top.a; + ~ +!!! error TS2339: Property 'a' does not exist on type 'Window'. + top.b; + ~ +!!! error TS2339: Property 'b' does not exist on type 'Window'. + + \ No newline at end of file diff --git a/tests/baselines/reference/globalThisVarDeclaration.js b/tests/baselines/reference/globalThisVarDeclaration.js new file mode 100644 index 00000000000..2ae75af703e --- /dev/null +++ b/tests/baselines/reference/globalThisVarDeclaration.js @@ -0,0 +1,59 @@ +//// [tests/cases/conformance/es2019/globalThisVarDeclaration.ts] //// + +//// [b.js] +var a = 10; +this.a; +this.b; +globalThis.a; +globalThis.b; + +// DOM access is not supported until the index signature is handled more strictly +self.a; +self.b; +window.a; +window.b; +top.a; +top.b; + +//// [actual.ts] +var b = 10; +this.a; +this.b; +globalThis.a; +globalThis.b; + +// same here -- no DOM access to globalThis yet +self.a; +self.b; +window.a; +window.b; +top.a; +top.b; + + + +//// [output.js] +var a = 10; +this.a; +this.b; +globalThis.a; +globalThis.b; +// DOM access is not supported until the index signature is handled more strictly +self.a; +self.b; +window.a; +window.b; +top.a; +top.b; +var b = 10; +this.a; +this.b; +globalThis.a; +globalThis.b; +// same here -- no DOM access to globalThis yet +self.a; +self.b; +window.a; +window.b; +top.a; +top.b; diff --git a/tests/baselines/reference/globalThisVarDeclaration.symbols b/tests/baselines/reference/globalThisVarDeclaration.symbols new file mode 100644 index 00000000000..b2d7feb37fd --- /dev/null +++ b/tests/baselines/reference/globalThisVarDeclaration.symbols @@ -0,0 +1,87 @@ +=== tests/cases/conformance/es2019/b.js === +var a = 10; +>a : Symbol(a, Decl(b.js, 0, 3)) + +this.a; +>this.a : Symbol(a, Decl(b.js, 0, 3)) +>this : Symbol(globalThis) +>a : Symbol(a, Decl(b.js, 0, 3)) + +this.b; +>this.b : Symbol(b, Decl(actual.ts, 0, 3)) +>this : Symbol(globalThis) +>b : Symbol(b, Decl(actual.ts, 0, 3)) + +globalThis.a; +>globalThis.a : Symbol(a, Decl(b.js, 0, 3)) +>globalThis : Symbol(globalThis) +>a : Symbol(a, Decl(b.js, 0, 3)) + +globalThis.b; +>globalThis.b : Symbol(b, Decl(actual.ts, 0, 3)) +>globalThis : Symbol(globalThis) +>b : Symbol(b, Decl(actual.ts, 0, 3)) + +// DOM access is not supported until the index signature is handled more strictly +self.a; +>self : Symbol(self, Decl(lib.dom.d.ts, --, --)) + +self.b; +>self : Symbol(self, Decl(lib.dom.d.ts, --, --)) + +window.a; +>window : Symbol(window, Decl(lib.dom.d.ts, --, --)) + +window.b; +>window : Symbol(window, Decl(lib.dom.d.ts, --, --)) + +top.a; +>top : Symbol(top, Decl(lib.dom.d.ts, --, --)) + +top.b; +>top : Symbol(top, Decl(lib.dom.d.ts, --, --)) + +=== tests/cases/conformance/es2019/actual.ts === +var b = 10; +>b : Symbol(b, Decl(actual.ts, 0, 3)) + +this.a; +>this.a : Symbol(a, Decl(b.js, 0, 3)) +>this : Symbol(globalThis) +>a : Symbol(a, Decl(b.js, 0, 3)) + +this.b; +>this.b : Symbol(b, Decl(actual.ts, 0, 3)) +>this : Symbol(globalThis) +>b : Symbol(b, Decl(actual.ts, 0, 3)) + +globalThis.a; +>globalThis.a : Symbol(a, Decl(b.js, 0, 3)) +>globalThis : Symbol(globalThis) +>a : Symbol(a, Decl(b.js, 0, 3)) + +globalThis.b; +>globalThis.b : Symbol(b, Decl(actual.ts, 0, 3)) +>globalThis : Symbol(globalThis) +>b : Symbol(b, Decl(actual.ts, 0, 3)) + +// same here -- no DOM access to globalThis yet +self.a; +>self : Symbol(self, Decl(lib.dom.d.ts, --, --)) + +self.b; +>self : Symbol(self, Decl(lib.dom.d.ts, --, --)) + +window.a; +>window : Symbol(window, Decl(lib.dom.d.ts, --, --)) + +window.b; +>window : Symbol(window, Decl(lib.dom.d.ts, --, --)) + +top.a; +>top : Symbol(top, Decl(lib.dom.d.ts, --, --)) + +top.b; +>top : Symbol(top, Decl(lib.dom.d.ts, --, --)) + + diff --git a/tests/baselines/reference/globalThisVarDeclaration.types b/tests/baselines/reference/globalThisVarDeclaration.types new file mode 100644 index 00000000000..9c520f667dc --- /dev/null +++ b/tests/baselines/reference/globalThisVarDeclaration.types @@ -0,0 +1,113 @@ +=== tests/cases/conformance/es2019/b.js === +var a = 10; +>a : number +>10 : 10 + +this.a; +>this.a : number +>this : typeof globalThis +>a : number + +this.b; +>this.b : number +>this : typeof globalThis +>b : number + +globalThis.a; +>globalThis.a : number +>globalThis : typeof globalThis +>a : number + +globalThis.b; +>globalThis.b : number +>globalThis : typeof globalThis +>b : number + +// DOM access is not supported until the index signature is handled more strictly +self.a; +>self.a : any +>self : Window +>a : any + +self.b; +>self.b : any +>self : Window +>b : any + +window.a; +>window.a : any +>window : Window +>a : any + +window.b; +>window.b : any +>window : Window +>b : any + +top.a; +>top.a : any +>top : Window +>a : any + +top.b; +>top.b : any +>top : Window +>b : any + +=== tests/cases/conformance/es2019/actual.ts === +var b = 10; +>b : number +>10 : 10 + +this.a; +>this.a : number +>this : typeof globalThis +>a : number + +this.b; +>this.b : number +>this : typeof globalThis +>b : number + +globalThis.a; +>globalThis.a : number +>globalThis : typeof globalThis +>a : number + +globalThis.b; +>globalThis.b : number +>globalThis : typeof globalThis +>b : number + +// same here -- no DOM access to globalThis yet +self.a; +>self.a : any +>self : Window +>a : any + +self.b; +>self.b : any +>self : Window +>b : any + +window.a; +>window.a : any +>window : Window +>a : any + +window.b; +>window.b : any +>window : Window +>b : any + +top.a; +>top.a : any +>top : Window +>a : any + +top.b; +>top.b : any +>top : Window +>b : any + + diff --git a/tests/baselines/reference/implicitAnyInCatch.symbols b/tests/baselines/reference/implicitAnyInCatch.symbols index 7ce3ac40f36..4f09ecdcbe5 100644 --- a/tests/baselines/reference/implicitAnyInCatch.symbols +++ b/tests/baselines/reference/implicitAnyInCatch.symbols @@ -8,6 +8,7 @@ try { } catch (error) { } for (var key in this) { } >key : Symbol(key, Decl(implicitAnyInCatch.ts, 4, 8)) +>this : Symbol(globalThis) class C { >C : Symbol(C, Decl(implicitAnyInCatch.ts, 4, 25)) diff --git a/tests/baselines/reference/implicitAnyInCatch.types b/tests/baselines/reference/implicitAnyInCatch.types index 6f70165407f..5619ec53622 100644 --- a/tests/baselines/reference/implicitAnyInCatch.types +++ b/tests/baselines/reference/implicitAnyInCatch.types @@ -13,7 +13,7 @@ try { } catch (error) { } for (var key in this) { } >key : string ->this : any +>this : typeof globalThis class C { >C : C diff --git a/tests/baselines/reference/inlineJsxFactoryDeclarationsLocalTypes.symbols b/tests/baselines/reference/inlineJsxFactoryDeclarationsLocalTypes.symbols index 25af733e40f..c53ac6b1948 100644 --- a/tests/baselines/reference/inlineJsxFactoryDeclarationsLocalTypes.symbols +++ b/tests/baselines/reference/inlineJsxFactoryDeclarationsLocalTypes.symbols @@ -127,6 +127,7 @@ export const MySFC = (props: {x: number, y: number, children?: predom.JSX.Elemen >props.y : Symbol(y, Decl(component.tsx, 3, 40)) >props : Symbol(props, Decl(component.tsx, 3, 22)) >y : Symbol(y, Decl(component.tsx, 3, 40)) +>this : Symbol(globalThis) >p : Symbol(predom.JSX.IntrinsicElements, Decl(renderer2.d.ts, 1, 19)) export class MyClass implements predom.JSX.Element { diff --git a/tests/baselines/reference/inlineJsxFactoryDeclarationsLocalTypes.types b/tests/baselines/reference/inlineJsxFactoryDeclarationsLocalTypes.types index a1c0e79909d..ab33876cbda 100644 --- a/tests/baselines/reference/inlineJsxFactoryDeclarationsLocalTypes.types +++ b/tests/baselines/reference/inlineJsxFactoryDeclarationsLocalTypes.types @@ -99,7 +99,7 @@ export const MySFC = (props: {x: number, y: number, children?: predom.JSX.Elemen >y : number >this.props.children : any >this.props : any ->this : any +>this : typeof globalThis >props : any >children : any >p : any diff --git a/tests/baselines/reference/jsxAttributeWithoutExpressionReact.symbols b/tests/baselines/reference/jsxAttributeWithoutExpressionReact.symbols index fc489ff899d..a12ac0b1c92 100644 --- a/tests/baselines/reference/jsxAttributeWithoutExpressionReact.symbols +++ b/tests/baselines/reference/jsxAttributeWithoutExpressionReact.symbols @@ -12,6 +12,7 @@ declare var React: any; } dataSource={this.state.ds} renderRow={}> >dataSource : Symbol(dataSource, Decl(jsxAttributeWithoutExpressionReact.tsx, 4, 5)) +>this : Symbol(globalThis) >renderRow : Symbol(renderRow, Decl(jsxAttributeWithoutExpressionReact.tsx, 4, 32)) diff --git a/tests/baselines/reference/jsxAttributeWithoutExpressionReact.types b/tests/baselines/reference/jsxAttributeWithoutExpressionReact.types index e5c192b4876..dac0e2c3df4 100644 --- a/tests/baselines/reference/jsxAttributeWithoutExpressionReact.types +++ b/tests/baselines/reference/jsxAttributeWithoutExpressionReact.types @@ -21,7 +21,7 @@ declare var React: any; >dataSource : any >this.state.ds : any >this.state : any ->this : any +>this : typeof globalThis >state : any >ds : any >renderRow : any diff --git a/tests/baselines/reference/jsxReactTestSuite.symbols b/tests/baselines/reference/jsxReactTestSuite.symbols index dfcc4c70bd8..8d656a8ecb1 100644 --- a/tests/baselines/reference/jsxReactTestSuite.symbols +++ b/tests/baselines/reference/jsxReactTestSuite.symbols @@ -39,6 +39,8 @@ declare var hasOwnProperty:any;
{this.props.children} +>this : Symbol(globalThis) +
;
@@ -57,6 +59,8 @@ declare var hasOwnProperty:any; >Composite : Symbol(Composite, Decl(jsxReactTestSuite.tsx, 2, 11)) {this.props.children} +>this : Symbol(globalThis) + ; >Composite : Symbol(Composite, Decl(jsxReactTestSuite.tsx, 2, 11)) @@ -154,6 +158,7 @@ var x = >Component : Symbol(Component, Decl(jsxReactTestSuite.tsx, 1, 11)) {...this.props} sound="moo" />; +>this : Symbol(globalThis) >sound : Symbol(sound, Decl(jsxReactTestSuite.tsx, 93, 19)) ; diff --git a/tests/baselines/reference/jsxReactTestSuite.types b/tests/baselines/reference/jsxReactTestSuite.types index 3637a21c268..dae8b8ae912 100644 --- a/tests/baselines/reference/jsxReactTestSuite.types +++ b/tests/baselines/reference/jsxReactTestSuite.types @@ -47,7 +47,7 @@ declare var hasOwnProperty:any; {this.props.children} >this.props.children : any >this.props : any ->this : any +>this : typeof globalThis >props : any >children : any @@ -89,7 +89,7 @@ declare var hasOwnProperty:any; {this.props.children} >this.props.children : any >this.props : any ->this : any +>this : typeof globalThis >props : any >children : any @@ -262,7 +262,7 @@ var x = {...this.props} sound="moo" />; >this.props : any ->this : any +>this : typeof globalThis >props : any >sound : string diff --git a/tests/baselines/reference/multiLinePropertyAccessAndArrowFunctionIndent1.symbols b/tests/baselines/reference/multiLinePropertyAccessAndArrowFunctionIndent1.symbols index 306e629e82d..e906195f9b1 100644 --- a/tests/baselines/reference/multiLinePropertyAccessAndArrowFunctionIndent1.symbols +++ b/tests/baselines/reference/multiLinePropertyAccessAndArrowFunctionIndent1.symbols @@ -1,9 +1,12 @@ === tests/cases/compiler/multiLinePropertyAccessAndArrowFunctionIndent1.ts === return this.edit(role) +>this : Symbol(globalThis) + .then((role: Role) => >role : Symbol(role, Decl(multiLinePropertyAccessAndArrowFunctionIndent1.ts, 1, 11)) this.roleService.add(role) +>this : Symbol(globalThis) >role : Symbol(role, Decl(multiLinePropertyAccessAndArrowFunctionIndent1.ts, 1, 11)) .then((data: ng.IHttpPromiseCallbackArg) => data.data)); diff --git a/tests/baselines/reference/multiLinePropertyAccessAndArrowFunctionIndent1.types b/tests/baselines/reference/multiLinePropertyAccessAndArrowFunctionIndent1.types index 5347dbb876d..9f35e8fff57 100644 --- a/tests/baselines/reference/multiLinePropertyAccessAndArrowFunctionIndent1.types +++ b/tests/baselines/reference/multiLinePropertyAccessAndArrowFunctionIndent1.types @@ -4,7 +4,7 @@ return this.edit(role) >this.edit(role) .then : any >this.edit(role) : any >this.edit : any ->this : any +>this : typeof globalThis >edit : any >role : any @@ -19,7 +19,7 @@ return this.edit(role) >this.roleService.add(role) : any >this.roleService.add : any >this.roleService : any ->this : any +>this : typeof globalThis >roleService : any >add : any >role : any diff --git a/tests/baselines/reference/noImplicitThisFunctions.errors.txt b/tests/baselines/reference/noImplicitThisFunctions.errors.txt index aac8faa566c..8fb99eb2724 100644 --- a/tests/baselines/reference/noImplicitThisFunctions.errors.txt +++ b/tests/baselines/reference/noImplicitThisFunctions.errors.txt @@ -1,6 +1,6 @@ tests/cases/compiler/noImplicitThisFunctions.ts(13,12): error TS2683: 'this' implicitly has type 'any' because it does not have a type annotation. -tests/cases/compiler/noImplicitThisFunctions.ts(17,38): error TS7041: The containing arrow function captures the global value of 'this' which implicitly has type 'any'. -tests/cases/compiler/noImplicitThisFunctions.ts(18,22): error TS7041: The containing arrow function captures the global value of 'this' which implicitly has type 'any'. +tests/cases/compiler/noImplicitThisFunctions.ts(17,38): error TS7041: The containing arrow function captures the global value of 'this'. +tests/cases/compiler/noImplicitThisFunctions.ts(18,22): error TS7041: The containing arrow function captures the global value of 'this'. tests/cases/compiler/noImplicitThisFunctions.ts(20,36): error TS2683: 'this' implicitly has type 'any' because it does not have a type annotation. tests/cases/compiler/noImplicitThisFunctions.ts(21,50): error TS2683: 'this' implicitly has type 'any' because it does not have a type annotation. @@ -26,10 +26,10 @@ tests/cases/compiler/noImplicitThisFunctions.ts(21,50): error TS2683: 'this' imp // error: `this` is `window`, but is still of type `any` let f4: (b: number) => number = b => this.c + b; ~~~~ -!!! error TS7041: The containing arrow function captures the global value of 'this' which implicitly has type 'any'. +!!! error TS7041: The containing arrow function captures the global value of 'this'. let f5 = () => () => this; ~~~~ -!!! error TS7041: The containing arrow function captures the global value of 'this' which implicitly has type 'any'. +!!! error TS7041: The containing arrow function captures the global value of 'this'. let f6 = function() { return () => this; }; ~~~~ diff --git a/tests/baselines/reference/noImplicitThisFunctions.symbols b/tests/baselines/reference/noImplicitThisFunctions.symbols index d8d937893f3..a86b117f910 100644 --- a/tests/baselines/reference/noImplicitThisFunctions.symbols +++ b/tests/baselines/reference/noImplicitThisFunctions.symbols @@ -31,10 +31,12 @@ let f4: (b: number) => number = b => this.c + b; >f4 : Symbol(f4, Decl(noImplicitThisFunctions.ts, 16, 3)) >b : Symbol(b, Decl(noImplicitThisFunctions.ts, 16, 9)) >b : Symbol(b, Decl(noImplicitThisFunctions.ts, 16, 31)) +>this : Symbol(globalThis) >b : Symbol(b, Decl(noImplicitThisFunctions.ts, 16, 31)) let f5 = () => () => this; >f5 : Symbol(f5, Decl(noImplicitThisFunctions.ts, 17, 3)) +>this : Symbol(globalThis) let f6 = function() { return () => this; }; >f6 : Symbol(f6, Decl(noImplicitThisFunctions.ts, 19, 3)) diff --git a/tests/baselines/reference/noImplicitThisFunctions.types b/tests/baselines/reference/noImplicitThisFunctions.types index f5b93fa9efb..639e84f650b 100644 --- a/tests/baselines/reference/noImplicitThisFunctions.types +++ b/tests/baselines/reference/noImplicitThisFunctions.types @@ -42,15 +42,15 @@ let f4: (b: number) => number = b => this.c + b; >b : number >this.c + b : any >this.c : any ->this : any +>this : typeof globalThis >c : any >b : number let f5 = () => () => this; ->f5 : () => () => any ->() => () => this : () => () => any ->() => this : () => any ->this : any +>f5 : () => () => typeof globalThis +>() => () => this : () => () => typeof globalThis +>() => this : () => typeof globalThis +>this : typeof globalThis let f6 = function() { return () => this; }; >f6 : () => () => any diff --git a/tests/baselines/reference/parserCommaInTypeMemberList2.symbols b/tests/baselines/reference/parserCommaInTypeMemberList2.symbols index ffaac46fd27..9bc7a392292 100644 --- a/tests/baselines/reference/parserCommaInTypeMemberList2.symbols +++ b/tests/baselines/reference/parserCommaInTypeMemberList2.symbols @@ -5,4 +5,5 @@ var s = $.extend< { workItem: any }, { workItem: any, width: string }>({ workIte >workItem : Symbol(workItem, Decl(parserCommaInTypeMemberList2.ts, 0, 38)) >width : Symbol(width, Decl(parserCommaInTypeMemberList2.ts, 0, 53)) >workItem : Symbol(workItem, Decl(parserCommaInTypeMemberList2.ts, 0, 72)) +>this : Symbol(globalThis) diff --git a/tests/baselines/reference/parserCommaInTypeMemberList2.types b/tests/baselines/reference/parserCommaInTypeMemberList2.types index cfa270d9838..0b172848ccd 100644 --- a/tests/baselines/reference/parserCommaInTypeMemberList2.types +++ b/tests/baselines/reference/parserCommaInTypeMemberList2.types @@ -11,7 +11,7 @@ var s = $.extend< { workItem: any }, { workItem: any, width: string }>({ workIte >{ workItem: this._workItem } : { workItem: any; } >workItem : any >this._workItem : any ->this : any +>this : typeof globalThis >_workItem : any >{} : {} diff --git a/tests/baselines/reference/parserConditionalExpression1.symbols b/tests/baselines/reference/parserConditionalExpression1.symbols index e271c68b4a0..91453101af1 100644 --- a/tests/baselines/reference/parserConditionalExpression1.symbols +++ b/tests/baselines/reference/parserConditionalExpression1.symbols @@ -1,3 +1,6 @@ === tests/cases/conformance/parser/ecmascript5/Expressions/parserConditionalExpression1.ts === (a=this.R[c])?a.JW||(a.e5(this,c),a.JW=_.l):this.A -No type information for this code. \ No newline at end of file +>this : Symbol(globalThis) +>this : Symbol(globalThis) +>this : Symbol(globalThis) + diff --git a/tests/baselines/reference/parserConditionalExpression1.types b/tests/baselines/reference/parserConditionalExpression1.types index 930d744d48a..d0fb5556033 100644 --- a/tests/baselines/reference/parserConditionalExpression1.types +++ b/tests/baselines/reference/parserConditionalExpression1.types @@ -6,7 +6,7 @@ >a : any >this.R[c] : any >this.R : any ->this : any +>this : typeof globalThis >R : any >c : any >a.JW||(a.e5(this,c),a.JW=_.l) : any @@ -19,7 +19,7 @@ >a.e5 : any >a : any >e5 : any ->this : any +>this : typeof globalThis >c : any >a.JW=_.l : any >a.JW : any @@ -29,6 +29,6 @@ >_ : any >l : any >this.A : any ->this : any +>this : typeof globalThis >A : any diff --git a/tests/baselines/reference/parserForStatement8.errors.txt b/tests/baselines/reference/parserForStatement8.errors.txt index 21ea55e3b09..ac04ed5e548 100644 --- a/tests/baselines/reference/parserForStatement8.errors.txt +++ b/tests/baselines/reference/parserForStatement8.errors.txt @@ -1,11 +1,11 @@ -tests/cases/conformance/parser/ecmascript5/Statements/parserForStatement8.ts(1,6): error TS2406: The left-hand side of a 'for...in' statement must be a variable or a property access. +tests/cases/conformance/parser/ecmascript5/Statements/parserForStatement8.ts(1,6): error TS2405: The left-hand side of a 'for...in' statement must be of type 'string' or 'any'. tests/cases/conformance/parser/ecmascript5/Statements/parserForStatement8.ts(1,14): error TS2304: Cannot find name 'b'. ==== tests/cases/conformance/parser/ecmascript5/Statements/parserForStatement8.ts (2 errors) ==== for (this in b) { ~~~~ -!!! error TS2406: The left-hand side of a 'for...in' statement must be a variable or a property access. +!!! error TS2405: The left-hand side of a 'for...in' statement must be of type 'string' or 'any'. ~ !!! error TS2304: Cannot find name 'b'. } \ No newline at end of file diff --git a/tests/baselines/reference/parserForStatement8.symbols b/tests/baselines/reference/parserForStatement8.symbols index 4e34f8b90c9..2133f54f57c 100644 --- a/tests/baselines/reference/parserForStatement8.symbols +++ b/tests/baselines/reference/parserForStatement8.symbols @@ -1,4 +1,4 @@ === tests/cases/conformance/parser/ecmascript5/Statements/parserForStatement8.ts === for (this in b) { -No type information for this code.} -No type information for this code. \ No newline at end of file +>this : Symbol(globalThis) +} diff --git a/tests/baselines/reference/parserForStatement8.types b/tests/baselines/reference/parserForStatement8.types index 0a520528759..72572e68cfc 100644 --- a/tests/baselines/reference/parserForStatement8.types +++ b/tests/baselines/reference/parserForStatement8.types @@ -1,5 +1,5 @@ === tests/cases/conformance/parser/ecmascript5/Statements/parserForStatement8.ts === for (this in b) { ->this : any +>this : typeof globalThis >b : any } diff --git a/tests/baselines/reference/parserModifierOnStatementInBlock2.symbols b/tests/baselines/reference/parserModifierOnStatementInBlock2.symbols index c118eff4a86..daf115443ae 100644 --- a/tests/baselines/reference/parserModifierOnStatementInBlock2.symbols +++ b/tests/baselines/reference/parserModifierOnStatementInBlock2.symbols @@ -2,5 +2,6 @@ { declare var x = this; >x : Symbol(x, Decl(parserModifierOnStatementInBlock2.ts, 1, 14)) +>this : Symbol(globalThis) } diff --git a/tests/baselines/reference/parserModifierOnStatementInBlock2.types b/tests/baselines/reference/parserModifierOnStatementInBlock2.types index a74d3a0c544..3bb3aee1cf9 100644 --- a/tests/baselines/reference/parserModifierOnStatementInBlock2.types +++ b/tests/baselines/reference/parserModifierOnStatementInBlock2.types @@ -1,7 +1,7 @@ === tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserModifierOnStatementInBlock2.ts === { declare var x = this; ->x : any ->this : any +>x : typeof globalThis +>this : typeof globalThis } diff --git a/tests/baselines/reference/parserStrictMode16.symbols b/tests/baselines/reference/parserStrictMode16.symbols index 655201fbea2..bef54a8af99 100644 --- a/tests/baselines/reference/parserStrictMode16.symbols +++ b/tests/baselines/reference/parserStrictMode16.symbols @@ -1,7 +1,8 @@ === tests/cases/conformance/parser/ecmascript5/StrictMode/parserStrictMode16.ts === "use strict"; -No type information for this code.delete this; -No type information for this code.delete 1; -No type information for this code.delete null; -No type information for this code.delete "a"; -No type information for this code. \ No newline at end of file +delete this; +>this : Symbol(globalThis) + +delete 1; +delete null; +delete "a"; diff --git a/tests/baselines/reference/parserStrictMode16.types b/tests/baselines/reference/parserStrictMode16.types index fbe701f374b..94c8a6a6bd7 100644 --- a/tests/baselines/reference/parserStrictMode16.types +++ b/tests/baselines/reference/parserStrictMode16.types @@ -4,7 +4,7 @@ delete this; >delete this : boolean ->this : any +>this : typeof globalThis delete 1; >delete 1 : boolean diff --git a/tests/baselines/reference/parserUnaryExpression1.errors.txt b/tests/baselines/reference/parserUnaryExpression1.errors.txt index 278960d53f3..40019965512 100644 --- a/tests/baselines/reference/parserUnaryExpression1.errors.txt +++ b/tests/baselines/reference/parserUnaryExpression1.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/parser/ecmascript5/Expressions/parserUnaryExpression1.ts(1,3): error TS2357: The operand of an increment or decrement operator must be a variable or a property access. +tests/cases/conformance/parser/ecmascript5/Expressions/parserUnaryExpression1.ts(1,3): error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. ==== tests/cases/conformance/parser/ecmascript5/Expressions/parserUnaryExpression1.ts (1 errors) ==== ++this; ~~~~ -!!! error TS2357: The operand of an increment or decrement operator must be a variable or a property access. \ No newline at end of file +!!! error TS2356: An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type. \ No newline at end of file diff --git a/tests/baselines/reference/parserUnaryExpression1.symbols b/tests/baselines/reference/parserUnaryExpression1.symbols index 2311212b63d..053c922f947 100644 --- a/tests/baselines/reference/parserUnaryExpression1.symbols +++ b/tests/baselines/reference/parserUnaryExpression1.symbols @@ -1,3 +1,4 @@ === tests/cases/conformance/parser/ecmascript5/Expressions/parserUnaryExpression1.ts === ++this; -No type information for this code. \ No newline at end of file +>this : Symbol(globalThis) + diff --git a/tests/baselines/reference/parserUnaryExpression1.types b/tests/baselines/reference/parserUnaryExpression1.types index 5803ac1f1f8..534dad66474 100644 --- a/tests/baselines/reference/parserUnaryExpression1.types +++ b/tests/baselines/reference/parserUnaryExpression1.types @@ -1,5 +1,5 @@ === tests/cases/conformance/parser/ecmascript5/Expressions/parserUnaryExpression1.ts === ++this; >++this : number ->this : any +>this : typeof globalThis diff --git a/tests/baselines/reference/propertyWrappedInTry.symbols b/tests/baselines/reference/propertyWrappedInTry.symbols index cce74c0981b..4d570fee1bb 100644 --- a/tests/baselines/reference/propertyWrappedInTry.symbols +++ b/tests/baselines/reference/propertyWrappedInTry.symbols @@ -14,6 +14,7 @@ class Foo { public baz() { return this.bar; // doesn't get rewritten to Foo.bar. +>this : Symbol(globalThis) } diff --git a/tests/baselines/reference/propertyWrappedInTry.types b/tests/baselines/reference/propertyWrappedInTry.types index 29be27edee9..8138f41091f 100644 --- a/tests/baselines/reference/propertyWrappedInTry.types +++ b/tests/baselines/reference/propertyWrappedInTry.types @@ -21,7 +21,7 @@ class Foo { return this.bar; // doesn't get rewritten to Foo.bar. >this.bar : any ->this : any +>this : typeof globalThis >bar : any } diff --git a/tests/baselines/reference/thisInInvalidContexts.errors.txt b/tests/baselines/reference/thisInInvalidContexts.errors.txt index 3581d6d6f29..7a357e1327e 100644 --- a/tests/baselines/reference/thisInInvalidContexts.errors.txt +++ b/tests/baselines/reference/thisInInvalidContexts.errors.txt @@ -3,11 +3,12 @@ tests/cases/conformance/expressions/thisKeyword/thisInInvalidContexts.ts(14,15): tests/cases/conformance/expressions/thisKeyword/thisInInvalidContexts.ts(22,15): error TS17009: 'super' must be called before accessing 'this' in the constructor of a derived class. tests/cases/conformance/expressions/thisKeyword/thisInInvalidContexts.ts(28,13): error TS2331: 'this' cannot be referenced in a module or namespace body. tests/cases/conformance/expressions/thisKeyword/thisInInvalidContexts.ts(36,13): error TS2526: A 'this' type is available only in a non-static member of a class or interface. +tests/cases/conformance/expressions/thisKeyword/thisInInvalidContexts.ts(38,25): error TS2507: Type 'typeof globalThis' is not a constructor function type. tests/cases/conformance/expressions/thisKeyword/thisInInvalidContexts.ts(44,9): error TS2332: 'this' cannot be referenced in current location. tests/cases/conformance/expressions/thisKeyword/thisInInvalidContexts.ts(45,9): error TS2332: 'this' cannot be referenced in current location. -==== tests/cases/conformance/expressions/thisKeyword/thisInInvalidContexts.ts (7 errors) ==== +==== tests/cases/conformance/expressions/thisKeyword/thisInInvalidContexts.ts (8 errors) ==== //'this' in static member initializer class ErrClass1 { static t = this; // Error @@ -56,6 +57,8 @@ tests/cases/conformance/expressions/thisKeyword/thisInInvalidContexts.ts(45,9): !!! error TS2526: A 'this' type is available only in a non-static member of a class or interface. class ErrClass3 extends this { + ~~~~ +!!! error TS2507: Type 'typeof globalThis' is not a constructor function type. } diff --git a/tests/baselines/reference/thisInInvalidContexts.symbols b/tests/baselines/reference/thisInInvalidContexts.symbols index 417b9cc5ea8..7fecdf73f43 100644 --- a/tests/baselines/reference/thisInInvalidContexts.symbols +++ b/tests/baselines/reference/thisInInvalidContexts.symbols @@ -69,6 +69,7 @@ genericFunc(undefined); // Should be an error class ErrClass3 extends this { >ErrClass3 : Symbol(ErrClass3, Decl(thisInInvalidContexts.ts, 35, 29)) +>this : Symbol(globalThis) } diff --git a/tests/baselines/reference/thisInInvalidContexts.types b/tests/baselines/reference/thisInInvalidContexts.types index 672a8fe58c4..6f35006b6c1 100644 --- a/tests/baselines/reference/thisInInvalidContexts.types +++ b/tests/baselines/reference/thisInInvalidContexts.types @@ -72,7 +72,7 @@ genericFunc(undefined); // Should be an error class ErrClass3 extends this { >ErrClass3 : ErrClass3 ->this : any +>this : typeof globalThis } diff --git a/tests/baselines/reference/thisInInvalidContextsExternalModule.errors.txt b/tests/baselines/reference/thisInInvalidContextsExternalModule.errors.txt index f89b2897892..4cfd109b00e 100644 --- a/tests/baselines/reference/thisInInvalidContextsExternalModule.errors.txt +++ b/tests/baselines/reference/thisInInvalidContextsExternalModule.errors.txt @@ -3,11 +3,12 @@ tests/cases/conformance/expressions/thisKeyword/thisInInvalidContextsExternalMod tests/cases/conformance/expressions/thisKeyword/thisInInvalidContextsExternalModule.ts(22,15): error TS17009: 'super' must be called before accessing 'this' in the constructor of a derived class. tests/cases/conformance/expressions/thisKeyword/thisInInvalidContextsExternalModule.ts(28,13): error TS2331: 'this' cannot be referenced in a module or namespace body. tests/cases/conformance/expressions/thisKeyword/thisInInvalidContextsExternalModule.ts(36,13): error TS2526: A 'this' type is available only in a non-static member of a class or interface. +tests/cases/conformance/expressions/thisKeyword/thisInInvalidContextsExternalModule.ts(38,25): error TS2507: Type 'typeof globalThis' is not a constructor function type. tests/cases/conformance/expressions/thisKeyword/thisInInvalidContextsExternalModule.ts(44,9): error TS2332: 'this' cannot be referenced in current location. tests/cases/conformance/expressions/thisKeyword/thisInInvalidContextsExternalModule.ts(45,9): error TS2332: 'this' cannot be referenced in current location. -==== tests/cases/conformance/expressions/thisKeyword/thisInInvalidContextsExternalModule.ts (7 errors) ==== +==== tests/cases/conformance/expressions/thisKeyword/thisInInvalidContextsExternalModule.ts (8 errors) ==== //'this' in static member initializer class ErrClass1 { static t = this; // Error @@ -56,6 +57,8 @@ tests/cases/conformance/expressions/thisKeyword/thisInInvalidContextsExternalMod !!! error TS2526: A 'this' type is available only in a non-static member of a class or interface. class ErrClass3 extends this { + ~~~~ +!!! error TS2507: Type 'typeof globalThis' is not a constructor function type. } diff --git a/tests/baselines/reference/thisInInvalidContextsExternalModule.symbols b/tests/baselines/reference/thisInInvalidContextsExternalModule.symbols index 9cf261fa672..ad52fbdabeb 100644 --- a/tests/baselines/reference/thisInInvalidContextsExternalModule.symbols +++ b/tests/baselines/reference/thisInInvalidContextsExternalModule.symbols @@ -69,6 +69,7 @@ genericFunc(undefined); // Should be an error class ErrClass3 extends this { >ErrClass3 : Symbol(ErrClass3, Decl(thisInInvalidContextsExternalModule.ts, 35, 29)) +>this : Symbol(globalThis) } diff --git a/tests/baselines/reference/thisInInvalidContextsExternalModule.types b/tests/baselines/reference/thisInInvalidContextsExternalModule.types index cdc13173077..e6ad34c9a20 100644 --- a/tests/baselines/reference/thisInInvalidContextsExternalModule.types +++ b/tests/baselines/reference/thisInInvalidContextsExternalModule.types @@ -72,7 +72,7 @@ genericFunc(undefined); // Should be an error class ErrClass3 extends this { >ErrClass3 : ErrClass3 ->this : any +>this : typeof globalThis } diff --git a/tests/baselines/reference/thisTypeInFunctions.symbols b/tests/baselines/reference/thisTypeInFunctions.symbols index ad16785f288..c1dcdb9829d 100644 --- a/tests/baselines/reference/thisTypeInFunctions.symbols +++ b/tests/baselines/reference/thisTypeInFunctions.symbols @@ -126,6 +126,7 @@ let impl: I = { explicitVoid2: () => this.a, // ok, this: any because it refers to some outer object (window?) >explicitVoid2 : Symbol(explicitVoid2, Decl(thisTypeInFunctions.ts, 38, 10)) +>this : Symbol(globalThis) explicitVoid1() { return 12; }, >explicitVoid1 : Symbol(explicitVoid1, Decl(thisTypeInFunctions.ts, 39, 32)) @@ -365,6 +366,7 @@ let unboundToSpecified: (this: { y: number }, x: number) => number = x => x + th >x : Symbol(x, Decl(thisTypeInFunctions.ts, 92, 45)) >x : Symbol(x, Decl(thisTypeInFunctions.ts, 92, 68)) >x : Symbol(x, Decl(thisTypeInFunctions.ts, 92, 68)) +>this : Symbol(globalThis) let specifiedToSpecified: (this: {y: number}, x: number) => number = explicitStructural; >specifiedToSpecified : Symbol(specifiedToSpecified, Decl(thisTypeInFunctions.ts, 93, 3)) @@ -495,6 +497,9 @@ c.explicitC = m => m + this.n; >explicitC : Symbol(C.explicitC, Decl(thisTypeInFunctions.ts, 8, 5)) >m : Symbol(m, Decl(thisTypeInFunctions.ts, 117, 13)) >m : Symbol(m, Decl(thisTypeInFunctions.ts, 117, 13)) +>this.n : Symbol(n, Decl(thisTypeInFunctions.ts, 190, 3)) +>this : Symbol(globalThis) +>n : Symbol(n, Decl(thisTypeInFunctions.ts, 190, 3)) c.explicitThis = m => m + this.n; >c.explicitThis : Symbol(C.explicitThis, Decl(thisTypeInFunctions.ts, 5, 14)) @@ -502,6 +507,9 @@ c.explicitThis = m => m + this.n; >explicitThis : Symbol(C.explicitThis, Decl(thisTypeInFunctions.ts, 5, 14)) >m : Symbol(m, Decl(thisTypeInFunctions.ts, 118, 16)) >m : Symbol(m, Decl(thisTypeInFunctions.ts, 118, 16)) +>this.n : Symbol(n, Decl(thisTypeInFunctions.ts, 190, 3)) +>this : Symbol(globalThis) +>n : Symbol(n, Decl(thisTypeInFunctions.ts, 190, 3)) c.explicitProperty = m => m + this.n; >c.explicitProperty : Symbol(C.explicitProperty, Decl(thisTypeInFunctions.ts, 11, 5)) @@ -509,6 +517,9 @@ c.explicitProperty = m => m + this.n; >explicitProperty : Symbol(C.explicitProperty, Decl(thisTypeInFunctions.ts, 11, 5)) >m : Symbol(m, Decl(thisTypeInFunctions.ts, 119, 20)) >m : Symbol(m, Decl(thisTypeInFunctions.ts, 119, 20)) +>this.n : Symbol(n, Decl(thisTypeInFunctions.ts, 190, 3)) +>this : Symbol(globalThis) +>n : Symbol(n, Decl(thisTypeInFunctions.ts, 190, 3)) //NOTE: this=C here, I guess? c.explicitThis = explicitCFunction; diff --git a/tests/baselines/reference/thisTypeInFunctions.types b/tests/baselines/reference/thisTypeInFunctions.types index caf4e9a5971..7408a764f1a 100644 --- a/tests/baselines/reference/thisTypeInFunctions.types +++ b/tests/baselines/reference/thisTypeInFunctions.types @@ -137,7 +137,7 @@ let impl: I = { >explicitVoid2 : () => any >() => this.a : () => any >this.a : any ->this : any +>this : typeof globalThis >a : any explicitVoid1() { return 12; }, @@ -431,7 +431,7 @@ let unboundToSpecified: (this: { y: number }, x: number) => number = x => x + th >x + this.y : any >x : number >this.y : any ->this : any +>this : typeof globalThis >y : any let specifiedToSpecified: (this: {y: number}, x: number) => number = explicitStructural; @@ -580,43 +580,43 @@ c.explicitProperty = m => m; // this inside lambdas refer to outer scope // the outer-scoped lambda at top-level is still just `any` c.explicitC = m => m + this.n; ->c.explicitC = m => m + this.n : (this: C, m: number) => any +>c.explicitC = m => m + this.n : (this: C, m: number) => number >c.explicitC : (this: C, m: number) => number >c : C >explicitC : (this: C, m: number) => number ->m => m + this.n : (this: C, m: number) => any +>m => m + this.n : (this: C, m: number) => number >m : number ->m + this.n : any +>m + this.n : number >m : number ->this.n : any ->this : any ->n : any +>this.n : number +>this : typeof globalThis +>n : number c.explicitThis = m => m + this.n; ->c.explicitThis = m => m + this.n : (this: C, m: number) => any +>c.explicitThis = m => m + this.n : (this: C, m: number) => number >c.explicitThis : (this: C, m: number) => number >c : C >explicitThis : (this: C, m: number) => number ->m => m + this.n : (this: C, m: number) => any +>m => m + this.n : (this: C, m: number) => number >m : number ->m + this.n : any +>m + this.n : number >m : number ->this.n : any ->this : any ->n : any +>this.n : number +>this : typeof globalThis +>n : number c.explicitProperty = m => m + this.n; ->c.explicitProperty = m => m + this.n : (this: { n: number; }, m: number) => any +>c.explicitProperty = m => m + this.n : (this: { n: number; }, m: number) => number >c.explicitProperty : (this: { n: number; }, m: number) => number >c : C >explicitProperty : (this: { n: number; }, m: number) => number ->m => m + this.n : (this: { n: number; }, m: number) => any +>m => m + this.n : (this: { n: number; }, m: number) => number >m : number ->m + this.n : any +>m + this.n : number >m : number ->this.n : any ->this : any ->n : any +>this.n : number +>this : typeof globalThis +>n : number //NOTE: this=C here, I guess? c.explicitThis = explicitCFunction; diff --git a/tests/baselines/reference/thisTypeInFunctionsNegative.symbols b/tests/baselines/reference/thisTypeInFunctionsNegative.symbols index 024ae663a9d..14566bbf946 100644 --- a/tests/baselines/reference/thisTypeInFunctionsNegative.symbols +++ b/tests/baselines/reference/thisTypeInFunctionsNegative.symbols @@ -134,6 +134,7 @@ let impl: I = { }, explicitVoid2: () => this.a, // ok, `this:any` because it refers to an outer object >explicitVoid2 : Symbol(explicitVoid2, Decl(thisTypeInFunctionsNegative.ts, 39, 6)) +>this : Symbol(globalThis) explicitStructural: () => 12, >explicitStructural : Symbol(explicitStructural, Decl(thisTypeInFunctionsNegative.ts, 40, 32)) @@ -655,6 +656,7 @@ function initializer(this: C = new C()): number { return this.n; } >C : Symbol(C, Decl(thisTypeInFunctionsNegative.ts, 0, 0)) > : Symbol((Missing), Decl(thisTypeInFunctionsNegative.ts, 171, 30)) >C : Symbol(C, Decl(thisTypeInFunctionsNegative.ts, 171, 34)) +>this : Symbol(globalThis) // can't name parameters 'this' in a lambda. c.explicitProperty = (this, m) => m + this.n; @@ -664,6 +666,7 @@ c.explicitProperty = (this, m) => m + this.n; >this : Symbol(this, Decl(thisTypeInFunctionsNegative.ts, 174, 22)) >m : Symbol(m, Decl(thisTypeInFunctionsNegative.ts, 174, 27)) >m : Symbol(m, Decl(thisTypeInFunctionsNegative.ts, 174, 27)) +>this : Symbol(globalThis) const f2 = (this: {n: number}, m: number) => m + this.n; >f2 : Symbol(f2, Decl(thisTypeInFunctionsNegative.ts, 175, 5)) @@ -672,6 +675,7 @@ const f2 = (this: {n: number}, m: number) => m + this.n; >n : Symbol(n, Decl(thisTypeInFunctionsNegative.ts, 175, 22)) >m : Symbol(m, Decl(thisTypeInFunctionsNegative.ts, 175, 33)) >m : Symbol(m, Decl(thisTypeInFunctionsNegative.ts, 175, 33)) +>this : Symbol(globalThis) const f3 = async (this: {n: number}, m: number) => m + this.n; >f3 : Symbol(f3, Decl(thisTypeInFunctionsNegative.ts, 176, 5)) @@ -679,6 +683,7 @@ const f3 = async (this: {n: number}, m: number) => m + this.n; >n : Symbol(n, Decl(thisTypeInFunctionsNegative.ts, 176, 25)) >m : Symbol(m, Decl(thisTypeInFunctionsNegative.ts, 176, 36)) >m : Symbol(m, Decl(thisTypeInFunctionsNegative.ts, 176, 36)) +>this : Symbol(globalThis) const f4 = async (this: {n: number}, m: number) => m + this.n; >f4 : Symbol(f4, Decl(thisTypeInFunctionsNegative.ts, 177, 5)) @@ -687,4 +692,5 @@ const f4 = async (this: {n: number}, m: number) => m + this.n; >n : Symbol(n, Decl(thisTypeInFunctionsNegative.ts, 177, 28)) >m : Symbol(m, Decl(thisTypeInFunctionsNegative.ts, 177, 39)) >m : Symbol(m, Decl(thisTypeInFunctionsNegative.ts, 177, 39)) +>this : Symbol(globalThis) diff --git a/tests/baselines/reference/thisTypeInFunctionsNegative.types b/tests/baselines/reference/thisTypeInFunctionsNegative.types index 90a5f06ad40..3a86203772f 100644 --- a/tests/baselines/reference/thisTypeInFunctionsNegative.types +++ b/tests/baselines/reference/thisTypeInFunctionsNegative.types @@ -143,7 +143,7 @@ let impl: I = { >explicitVoid2 : () => any >() => this.a : () => any >this.a : any ->this : any +>this : typeof globalThis >a : any explicitStructural: () => 12, @@ -751,7 +751,7 @@ function initializer(this: C = new C()): number { return this.n; } > : any >number : any >this.n : any ->this : any +>this : typeof globalThis >n : any // can't name parameters 'this' in a lambda. @@ -766,7 +766,7 @@ c.explicitProperty = (this, m) => m + this.n; >m + this.n : any >m : number >this.n : any ->this : any +>this : typeof globalThis >n : any const f2 = (this: {n: number}, m: number) => m + this.n; @@ -778,7 +778,7 @@ const f2 = (this: {n: number}, m: number) => m + this.n; >m + this.n : any >m : number >this.n : any ->this : any +>this : typeof globalThis >n : any const f3 = async (this: {n: number}, m: number) => m + this.n; @@ -790,7 +790,7 @@ const f3 = async (this: {n: number}, m: number) => m + this.n; >m + this.n : any >m : number >this.n : any ->this : any +>this : typeof globalThis >n : any const f4 = async (this: {n: number}, m: number) => m + this.n; @@ -802,6 +802,6 @@ const f4 = async (this: {n: number}, m: number) => m + this.n; >m + this.n : any >m : number >this.n : any ->this : any +>this : typeof globalThis >n : any diff --git a/tests/baselines/reference/topLevelLambda2.symbols b/tests/baselines/reference/topLevelLambda2.symbols index 712d0a1611a..412a7c8a547 100644 --- a/tests/baselines/reference/topLevelLambda2.symbols +++ b/tests/baselines/reference/topLevelLambda2.symbols @@ -5,4 +5,7 @@ function foo(x:any) {} foo(()=>this.window); >foo : Symbol(foo, Decl(topLevelLambda2.ts, 0, 0)) +>this.window : Symbol(window, Decl(lib.dom.d.ts, --, --)) +>this : Symbol(globalThis) +>window : Symbol(window, Decl(lib.dom.d.ts, --, --)) diff --git a/tests/baselines/reference/topLevelLambda2.types b/tests/baselines/reference/topLevelLambda2.types index 7dcb909cdf9..ddca05514d0 100644 --- a/tests/baselines/reference/topLevelLambda2.types +++ b/tests/baselines/reference/topLevelLambda2.types @@ -6,8 +6,8 @@ function foo(x:any) {} foo(()=>this.window); >foo(()=>this.window) : void >foo : (x: any) => void ->()=>this.window : () => any ->this.window : any ->this : any ->window : any +>()=>this.window : () => Window +>this.window : Window +>this : typeof globalThis +>window : Window diff --git a/tests/baselines/reference/topLevelLambda3.symbols b/tests/baselines/reference/topLevelLambda3.symbols index 6ec9476ff74..7dd41958b7f 100644 --- a/tests/baselines/reference/topLevelLambda3.symbols +++ b/tests/baselines/reference/topLevelLambda3.symbols @@ -1,4 +1,7 @@ === tests/cases/compiler/topLevelLambda3.ts === var f = () => {this.window;} >f : Symbol(f, Decl(topLevelLambda3.ts, 0, 3)) +>this.window : Symbol(window, Decl(lib.dom.d.ts, --, --)) +>this : Symbol(globalThis) +>window : Symbol(window, Decl(lib.dom.d.ts, --, --)) diff --git a/tests/baselines/reference/topLevelLambda3.types b/tests/baselines/reference/topLevelLambda3.types index e96d40880fc..b2bb8f30bad 100644 --- a/tests/baselines/reference/topLevelLambda3.types +++ b/tests/baselines/reference/topLevelLambda3.types @@ -2,7 +2,7 @@ var f = () => {this.window;} >f : () => void >() => {this.window;} : () => void ->this.window : any ->this : any ->window : any +>this.window : Window +>this : typeof globalThis +>window : Window diff --git a/tests/baselines/reference/topLevelLambda4.symbols b/tests/baselines/reference/topLevelLambda4.symbols index a4f403a762f..202d1bf90d5 100644 --- a/tests/baselines/reference/topLevelLambda4.symbols +++ b/tests/baselines/reference/topLevelLambda4.symbols @@ -1,4 +1,7 @@ === tests/cases/compiler/topLevelLambda4.ts === export var x = () => this.window; >x : Symbol(x, Decl(topLevelLambda4.ts, 0, 10)) +>this.window : Symbol(window, Decl(lib.dom.d.ts, --, --)) +>this : Symbol(globalThis) +>window : Symbol(window, Decl(lib.dom.d.ts, --, --)) diff --git a/tests/baselines/reference/topLevelLambda4.types b/tests/baselines/reference/topLevelLambda4.types index f6c8752c267..081f5c47c5a 100644 --- a/tests/baselines/reference/topLevelLambda4.types +++ b/tests/baselines/reference/topLevelLambda4.types @@ -1,8 +1,8 @@ === tests/cases/compiler/topLevelLambda4.ts === export var x = () => this.window; ->x : () => any ->() => this.window : () => any ->this.window : any ->this : any ->window : any +>x : () => Window +>() => this.window : () => Window +>this.window : Window +>this : typeof globalThis +>window : Window diff --git a/tests/baselines/reference/topLevelThisAssignment.symbols b/tests/baselines/reference/topLevelThisAssignment.symbols index e9b94983bf2..4ac7e799848 100644 --- a/tests/baselines/reference/topLevelThisAssignment.symbols +++ b/tests/baselines/reference/topLevelThisAssignment.symbols @@ -1,10 +1,23 @@ === tests/cases/conformance/salsa/a.js === this.a = 10; -No type information for this code.this.a; -No type information for this code.a; -No type information for this code. -No type information for this code.=== tests/cases/conformance/salsa/b.js === +>this.a : Symbol(a, Decl(a.js, 0, 0)) +>this : Symbol(globalThis) +>a : Symbol(a, Decl(a.js, 0, 0)) + this.a; -No type information for this code.a; -No type information for this code. -No type information for this code. \ No newline at end of file +>this.a : Symbol(a, Decl(a.js, 0, 0)) +>this : Symbol(globalThis) +>a : Symbol(a, Decl(a.js, 0, 0)) + +a; +>a : Symbol(a, Decl(a.js, 0, 0)) + +=== tests/cases/conformance/salsa/b.js === +this.a; +>this.a : Symbol(a, Decl(a.js, 0, 0)) +>this : Symbol(globalThis) +>a : Symbol(a, Decl(a.js, 0, 0)) + +a; +>a : Symbol(a, Decl(a.js, 0, 0)) + diff --git a/tests/baselines/reference/topLevelThisAssignment.types b/tests/baselines/reference/topLevelThisAssignment.types index 92bb458b41f..11c7b5a82e1 100644 --- a/tests/baselines/reference/topLevelThisAssignment.types +++ b/tests/baselines/reference/topLevelThisAssignment.types @@ -1,25 +1,25 @@ === tests/cases/conformance/salsa/a.js === this.a = 10; >this.a = 10 : 10 ->this.a : any ->this : any ->a : any +>this.a : number +>this : typeof globalThis +>a : number >10 : 10 this.a; ->this.a : any ->this : any ->a : any +>this.a : number +>this : typeof globalThis +>a : number a; ->a : error +>a : number === tests/cases/conformance/salsa/b.js === this.a; ->this.a : any ->this : any ->a : any +>this.a : number +>this : typeof globalThis +>a : number a; ->a : error +>a : number diff --git a/tests/baselines/reference/tsxAttributeResolution15.errors.txt b/tests/baselines/reference/tsxAttributeResolution15.errors.txt index f4c9c14deb5..ca86178b578 100644 --- a/tests/baselines/reference/tsxAttributeResolution15.errors.txt +++ b/tests/baselines/reference/tsxAttributeResolution15.errors.txt @@ -1,8 +1,9 @@ tests/cases/conformance/jsx/file.tsx(11,10): error TS2322: Type '{ prop1: string; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. Property 'prop1' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes & { children?: ReactNode; }'. +tests/cases/conformance/jsx/file.tsx(14,44): error TS7017: Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature. -==== tests/cases/conformance/jsx/file.tsx (1 errors) ==== +==== tests/cases/conformance/jsx/file.tsx (2 errors) ==== import React = require('react'); class BigGreeter extends React.Component<{ }, {}> { @@ -20,4 +21,6 @@ tests/cases/conformance/jsx/file.tsx(11,10): error TS2322: Type '{ prop1: string // OK let b = { this.textInput = input; }} /> + ~~~~~~~~~ +!!! error TS7017: Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature. let c = \ No newline at end of file diff --git a/tests/baselines/reference/tsxAttributeResolution15.symbols b/tests/baselines/reference/tsxAttributeResolution15.symbols index 5c91d12a103..c366c93cef1 100644 --- a/tests/baselines/reference/tsxAttributeResolution15.symbols +++ b/tests/baselines/reference/tsxAttributeResolution15.symbols @@ -31,6 +31,7 @@ let b = { this.textInput = input; }} /> >BigGreeter : Symbol(BigGreeter, Decl(file.tsx, 0, 32)) >ref : Symbol(ref, Decl(file.tsx, 13, 19)) >input : Symbol(input, Decl(file.tsx, 13, 26)) +>this : Symbol(globalThis) >input : Symbol(input, Decl(file.tsx, 13, 26)) let c = diff --git a/tests/baselines/reference/tsxAttributeResolution15.types b/tests/baselines/reference/tsxAttributeResolution15.types index b95dcffcaf7..469f146cc45 100644 --- a/tests/baselines/reference/tsxAttributeResolution15.types +++ b/tests/baselines/reference/tsxAttributeResolution15.types @@ -37,7 +37,7 @@ let b = { this.textInput = input; }} /> >input : BigGreeter >this.textInput = input : BigGreeter >this.textInput : any ->this : any +>this : typeof globalThis >textInput : any >input : BigGreeter diff --git a/tests/baselines/reference/tsxSpreadAttributesResolution4.symbols b/tests/baselines/reference/tsxSpreadAttributesResolution4.symbols index e599665b156..cb357c8a20d 100644 --- a/tests/baselines/reference/tsxSpreadAttributesResolution4.symbols +++ b/tests/baselines/reference/tsxSpreadAttributesResolution4.symbols @@ -79,6 +79,7 @@ let e3 = { this.textInput = input; } }} /> >EmptyProp : Symbol(EmptyProp, Decl(file.tsx, 19, 30)) >ref : Symbol(ref, Decl(file.tsx, 31, 25)) >input : Symbol(input, Decl(file.tsx, 31, 32)) +>this : Symbol(globalThis) >input : Symbol(input, Decl(file.tsx, 31, 32)) let e4 = diff --git a/tests/baselines/reference/tsxSpreadAttributesResolution4.types b/tests/baselines/reference/tsxSpreadAttributesResolution4.types index 194993348dc..82173c0df83 100644 --- a/tests/baselines/reference/tsxSpreadAttributesResolution4.types +++ b/tests/baselines/reference/tsxSpreadAttributesResolution4.types @@ -89,7 +89,7 @@ let e3 = { this.textInput = input; } }} /> >input : EmptyProp >this.textInput = input : EmptyProp >this.textInput : any ->this : any +>this : typeof globalThis >textInput : any >input : EmptyProp diff --git a/tests/baselines/reference/typeFromPropertyAssignment23.symbols b/tests/baselines/reference/typeFromPropertyAssignment23.symbols index 2ba8651ea53..f28bf54ac7a 100644 --- a/tests/baselines/reference/typeFromPropertyAssignment23.symbols +++ b/tests/baselines/reference/typeFromPropertyAssignment23.symbols @@ -38,6 +38,8 @@ D.prototype.foo = () => { >foo : Symbol(D.foo, Decl(a.js, 14, 21)) this.n = 'not checked, so no error' +>this : Symbol(globalThis) +>n : Symbol(n, Decl(a.js, 15, 26)) } // post-class prototype assignments are trying to show that these properties are abstract diff --git a/tests/baselines/reference/typeFromPropertyAssignment23.types b/tests/baselines/reference/typeFromPropertyAssignment23.types index 4e540e3962f..03bf1d91776 100644 --- a/tests/baselines/reference/typeFromPropertyAssignment23.types +++ b/tests/baselines/reference/typeFromPropertyAssignment23.types @@ -46,7 +46,7 @@ D.prototype.foo = () => { this.n = 'not checked, so no error' >this.n = 'not checked, so no error' : "not checked, so no error" >this.n : any ->this : any +>this : typeof globalThis >n : any >'not checked, so no error' : "not checked, so no error" } diff --git a/tests/baselines/reference/typeFromPropertyAssignment9.symbols b/tests/baselines/reference/typeFromPropertyAssignment9.symbols index 27188c71b32..2ebec8f5204 100644 --- a/tests/baselines/reference/typeFromPropertyAssignment9.symbols +++ b/tests/baselines/reference/typeFromPropertyAssignment9.symbols @@ -118,6 +118,11 @@ min.nest = this.min.nest || function () { }; >min.nest : Symbol(min.nest, Decl(a.js, 29, 27), Decl(a.js, 31, 4)) >min : Symbol(min, Decl(a.js, 29, 3), Decl(a.js, 29, 27), Decl(a.js, 30, 44)) >nest : Symbol(min.nest, Decl(a.js, 29, 27), Decl(a.js, 31, 4)) +>this.min.nest : Symbol(min.nest, Decl(a.js, 29, 27), Decl(a.js, 31, 4)) +>this.min : Symbol(min, Decl(a.js, 29, 3), Decl(a.js, 29, 27), Decl(a.js, 30, 44)) +>this : Symbol(globalThis) +>min : Symbol(min, Decl(a.js, 29, 3), Decl(a.js, 29, 27), Decl(a.js, 30, 44)) +>nest : Symbol(min.nest, Decl(a.js, 29, 27), Decl(a.js, 31, 4)) min.nest.other = self.min.nest.other || class { }; >min.nest.other : Symbol(min.nest.other, Decl(a.js, 30, 44)) diff --git a/tests/baselines/reference/typeFromPropertyAssignment9.types b/tests/baselines/reference/typeFromPropertyAssignment9.types index b212f12bb17..c4f813f0a89 100644 --- a/tests/baselines/reference/typeFromPropertyAssignment9.types +++ b/tests/baselines/reference/typeFromPropertyAssignment9.types @@ -157,11 +157,11 @@ min.nest = this.min.nest || function () { }; >min : typeof min >nest : { (): void; other: typeof other; } >this.min.nest || function () { } : { (): void; other: typeof other; } ->this.min.nest : any ->this.min : any ->this : any ->min : any ->nest : any +>this.min.nest : { (): void; other: typeof other; } +>this.min : typeof min +>this : typeof globalThis +>min : typeof min +>nest : { (): void; other: typeof other; } >function () { } : { (): void; other: typeof other; } min.nest.other = self.min.nest.other || class { }; diff --git a/tests/baselines/reference/typeOfThis.errors.txt b/tests/baselines/reference/typeOfThis.errors.txt index 83d450570fc..b47207670cc 100644 --- a/tests/baselines/reference/typeOfThis.errors.txt +++ b/tests/baselines/reference/typeOfThis.errors.txt @@ -1,24 +1,16 @@ tests/cases/conformance/expressions/thisKeyword/typeOfThis.ts(14,13): error TS2403: Subsequent variable declarations must have the same type. Variable 't' must be of type 'this', but here has type 'MyTestClass'. tests/cases/conformance/expressions/thisKeyword/typeOfThis.ts(18,13): error TS2403: Subsequent variable declarations must have the same type. Variable 'p' must be of type 'this', but here has type 'MyTestClass'. -tests/cases/conformance/expressions/thisKeyword/typeOfThis.ts(22,9): error TS1056: Accessors are only available when targeting ECMAScript 5 and higher. tests/cases/conformance/expressions/thisKeyword/typeOfThis.ts(24,13): error TS2403: Subsequent variable declarations must have the same type. Variable 'p' must be of type 'this', but here has type 'MyTestClass'. -tests/cases/conformance/expressions/thisKeyword/typeOfThis.ts(27,9): error TS1056: Accessors are only available when targeting ECMAScript 5 and higher. tests/cases/conformance/expressions/thisKeyword/typeOfThis.ts(29,13): error TS2403: Subsequent variable declarations must have the same type. Variable 'p' must be of type 'this', but here has type 'MyTestClass'. tests/cases/conformance/expressions/thisKeyword/typeOfThis.ts(37,13): error TS2403: Subsequent variable declarations must have the same type. Variable 't' must be of type 'this', but here has type 'MyTestClass'. -tests/cases/conformance/expressions/thisKeyword/typeOfThis.ts(53,16): error TS1056: Accessors are only available when targeting ECMAScript 5 and higher. -tests/cases/conformance/expressions/thisKeyword/typeOfThis.ts(61,16): error TS1056: Accessors are only available when targeting ECMAScript 5 and higher. tests/cases/conformance/expressions/thisKeyword/typeOfThis.ts(83,13): error TS2403: Subsequent variable declarations must have the same type. Variable 't' must be of type 'this', but here has type 'MyGenericTestClass'. tests/cases/conformance/expressions/thisKeyword/typeOfThis.ts(87,13): error TS2403: Subsequent variable declarations must have the same type. Variable 'p' must be of type 'this', but here has type 'MyGenericTestClass'. -tests/cases/conformance/expressions/thisKeyword/typeOfThis.ts(91,9): error TS1056: Accessors are only available when targeting ECMAScript 5 and higher. tests/cases/conformance/expressions/thisKeyword/typeOfThis.ts(93,13): error TS2403: Subsequent variable declarations must have the same type. Variable 'p' must be of type 'this', but here has type 'MyGenericTestClass'. -tests/cases/conformance/expressions/thisKeyword/typeOfThis.ts(96,9): error TS1056: Accessors are only available when targeting ECMAScript 5 and higher. tests/cases/conformance/expressions/thisKeyword/typeOfThis.ts(98,13): error TS2403: Subsequent variable declarations must have the same type. Variable 'p' must be of type 'this', but here has type 'MyGenericTestClass'. tests/cases/conformance/expressions/thisKeyword/typeOfThis.ts(106,13): error TS2403: Subsequent variable declarations must have the same type. Variable 't' must be of type 'this', but here has type 'MyGenericTestClass'. -tests/cases/conformance/expressions/thisKeyword/typeOfThis.ts(122,16): error TS1056: Accessors are only available when targeting ECMAScript 5 and higher. -tests/cases/conformance/expressions/thisKeyword/typeOfThis.ts(130,16): error TS1056: Accessors are only available when targeting ECMAScript 5 and higher. -==== tests/cases/conformance/expressions/thisKeyword/typeOfThis.ts (18 errors) ==== +==== tests/cases/conformance/expressions/thisKeyword/typeOfThis.ts (10 errors) ==== class MyTestClass { private canary: number; static staticCanary: number; @@ -45,8 +37,6 @@ tests/cases/conformance/expressions/thisKeyword/typeOfThis.ts(130,16): error TS1 //type of 'this' in member accessor(get and set) body is the class instance type get prop() { - ~~~~ -!!! error TS1056: Accessors are only available when targeting ECMAScript 5 and higher. var p = this; var p: MyTestClass; ~ @@ -54,8 +44,6 @@ tests/cases/conformance/expressions/thisKeyword/typeOfThis.ts(130,16): error TS1 return this; } set prop(v) { - ~~~~ -!!! error TS1056: Accessors are only available when targeting ECMAScript 5 and higher. var p = this; var p: MyTestClass; ~ @@ -86,8 +74,6 @@ tests/cases/conformance/expressions/thisKeyword/typeOfThis.ts(130,16): error TS1 } static get staticProp() { - ~~~~~~~~~~ -!!! error TS1056: Accessors are only available when targeting ECMAScript 5 and higher. //type of 'this' in static accessor body is constructor function type var p = this; var p: typeof MyTestClass; @@ -96,8 +82,6 @@ tests/cases/conformance/expressions/thisKeyword/typeOfThis.ts(130,16): error TS1 return this; } static set staticProp(v: typeof MyTestClass) { - ~~~~~~~~~~ -!!! error TS1056: Accessors are only available when targeting ECMAScript 5 and higher. //type of 'this' in static accessor body is constructor function type var p = this; var p: typeof MyTestClass; @@ -132,8 +116,6 @@ tests/cases/conformance/expressions/thisKeyword/typeOfThis.ts(130,16): error TS1 //type of 'this' in member accessor(get and set) body is the class instance type get prop() { - ~~~~ -!!! error TS1056: Accessors are only available when targeting ECMAScript 5 and higher. var p = this; var p: MyGenericTestClass; ~ @@ -141,8 +123,6 @@ tests/cases/conformance/expressions/thisKeyword/typeOfThis.ts(130,16): error TS1 return this; } set prop(v) { - ~~~~ -!!! error TS1056: Accessors are only available when targeting ECMAScript 5 and higher. var p = this; var p: MyGenericTestClass; ~ @@ -173,8 +153,6 @@ tests/cases/conformance/expressions/thisKeyword/typeOfThis.ts(130,16): error TS1 } static get staticProp() { - ~~~~~~~~~~ -!!! error TS1056: Accessors are only available when targeting ECMAScript 5 and higher. //type of 'this' in static accessor body is constructor function type var p = this; var p: typeof MyGenericTestClass; @@ -183,8 +161,6 @@ tests/cases/conformance/expressions/thisKeyword/typeOfThis.ts(130,16): error TS1 return this; } static set staticProp(v: typeof MyGenericTestClass) { - ~~~~~~~~~~ -!!! error TS1056: Accessors are only available when targeting ECMAScript 5 and higher. //type of 'this' in static accessor body is constructor function type var p = this; var p: typeof MyGenericTestClass; @@ -215,19 +191,19 @@ tests/cases/conformance/expressions/thisKeyword/typeOfThis.ts(130,16): error TS1 this.spaaaaace = 4; } - //type of 'this' in a fat arrow expression param list is Any + //type of 'this' in a fat arrow expression param list is typeof globalThis var q2 = (s = this) => { - var s: any; + var s: typeof globalThis; s.spaaaaaaace = 4; - //type of 'this' in a fat arrow expression body is Any - var t: any; + //type of 'this' in a fat arrow expression body is typeof globalThis + var t: typeof globalThis; var t = this; this.spaaaaace = 4; } - //type of 'this' in global module is Any - var t: any; + //type of 'this' in global module is GlobalThis + var t: typeof globalThis; var t = this; this.spaaaaace = 4; diff --git a/tests/baselines/reference/typeOfThis.js b/tests/baselines/reference/typeOfThis.js index 42593bd3d2a..0ea8fc2f935 100644 --- a/tests/baselines/reference/typeOfThis.js +++ b/tests/baselines/reference/typeOfThis.js @@ -159,32 +159,30 @@ var q1 = function (s = this) { this.spaaaaace = 4; } -//type of 'this' in a fat arrow expression param list is Any +//type of 'this' in a fat arrow expression param list is typeof globalThis var q2 = (s = this) => { - var s: any; + var s: typeof globalThis; s.spaaaaaaace = 4; - //type of 'this' in a fat arrow expression body is Any - var t: any; + //type of 'this' in a fat arrow expression body is typeof globalThis + var t: typeof globalThis; var t = this; this.spaaaaace = 4; } -//type of 'this' in global module is Any -var t: any; +//type of 'this' in global module is GlobalThis +var t: typeof globalThis; var t = this; this.spaaaaace = 4; //// [typeOfThis.js] -var _this = this; -var MyTestClass = /** @class */ (function () { - function MyTestClass() { - var _this = this; - this.someFunc = function () { +class MyTestClass { + constructor() { + this.someFunc = () => { //type of 'this' in member variable initializer is the class instance type - var t = _this; + var t = this; var t; }; //type of 'this' in constructor body is the class instance type @@ -193,32 +191,26 @@ var MyTestClass = /** @class */ (function () { this.canary = 3; } //type of 'this' in member function param list is the class instance type - MyTestClass.prototype.memberFunc = function (t) { - if (t === void 0) { t = this; } + memberFunc(t = this) { var t; //type of 'this' in member function body is the class instance type var p = this; var p; - }; - Object.defineProperty(MyTestClass.prototype, "prop", { - //type of 'this' in member accessor(get and set) body is the class instance type - get: function () { - var p = this; - var p; - return this; - }, - set: function (v) { - var p = this; - var p; - p = v; - v = p; - }, - enumerable: true, - configurable: true - }); + } + //type of 'this' in member accessor(get and set) body is the class instance type + get prop() { + var p = this; + var p; + return this; + } + set prop(v) { + var p = this; + var p; + p = v; + v = p; + } //type of 'this' in static function param list is constructor function type - MyTestClass.staticFn = function (t) { - if (t === void 0) { t = this; } + static staticFn(t = this) { var t; var t = MyTestClass; t.staticCanary; @@ -227,34 +219,28 @@ var MyTestClass = /** @class */ (function () { var p; var p = MyTestClass; p.staticCanary; - }; - Object.defineProperty(MyTestClass, "staticProp", { - get: function () { - //type of 'this' in static accessor body is constructor function type - var p = this; - var p; - var p = MyTestClass; - p.staticCanary; - return this; - }, - set: function (v) { - //type of 'this' in static accessor body is constructor function type - var p = this; - var p; - var p = MyTestClass; - p.staticCanary; - }, - enumerable: true, - configurable: true - }); - return MyTestClass; -}()); -var MyGenericTestClass = /** @class */ (function () { - function MyGenericTestClass() { - var _this = this; - this.someFunc = function () { + } + static get staticProp() { + //type of 'this' in static accessor body is constructor function type + var p = this; + var p; + var p = MyTestClass; + p.staticCanary; + return this; + } + static set staticProp(v) { + //type of 'this' in static accessor body is constructor function type + var p = this; + var p; + var p = MyTestClass; + p.staticCanary; + } +} +class MyGenericTestClass { + constructor() { + this.someFunc = () => { //type of 'this' in member variable initializer is the class instance type - var t = _this; + var t = this; var t; }; //type of 'this' in constructor body is the class instance type @@ -263,32 +249,26 @@ var MyGenericTestClass = /** @class */ (function () { this.canary = 3; } //type of 'this' in member function param list is the class instance type - MyGenericTestClass.prototype.memberFunc = function (t) { - if (t === void 0) { t = this; } + memberFunc(t = this) { var t; //type of 'this' in member function body is the class instance type var p = this; var p; - }; - Object.defineProperty(MyGenericTestClass.prototype, "prop", { - //type of 'this' in member accessor(get and set) body is the class instance type - get: function () { - var p = this; - var p; - return this; - }, - set: function (v) { - var p = this; - var p; - p = v; - v = p; - }, - enumerable: true, - configurable: true - }); + } + //type of 'this' in member accessor(get and set) body is the class instance type + get prop() { + var p = this; + var p; + return this; + } + set prop(v) { + var p = this; + var p; + p = v; + v = p; + } //type of 'this' in static function param list is constructor function type - MyGenericTestClass.staticFn = function (t) { - if (t === void 0) { t = this; } + static staticFn(t = this) { var t; var t = MyGenericTestClass; t.staticCanary; @@ -297,31 +277,25 @@ var MyGenericTestClass = /** @class */ (function () { var p; var p = MyGenericTestClass; p.staticCanary; - }; - Object.defineProperty(MyGenericTestClass, "staticProp", { - get: function () { - //type of 'this' in static accessor body is constructor function type - var p = this; - var p; - var p = MyGenericTestClass; - p.staticCanary; - return this; - }, - set: function (v) { - //type of 'this' in static accessor body is constructor function type - var p = this; - var p; - var p = MyGenericTestClass; - p.staticCanary; - }, - enumerable: true, - configurable: true - }); - return MyGenericTestClass; -}()); + } + static get staticProp() { + //type of 'this' in static accessor body is constructor function type + var p = this; + var p; + var p = MyGenericTestClass; + p.staticCanary; + return this; + } + static set staticProp(v) { + //type of 'this' in static accessor body is constructor function type + var p = this; + var p; + var p = MyGenericTestClass; + p.staticCanary; + } +} //type of 'this' in a function declaration param list is Any -function fn(s) { - if (s === void 0) { s = this; } +function fn(s = this) { var s; s.spaaaaaaace = 4; //type of 'this' in a function declaration body is Any @@ -330,8 +304,7 @@ function fn(s) { this.spaaaaace = 4; } //type of 'this' in a function expression param list list is Any -var q1 = function (s) { - if (s === void 0) { s = this; } +var q1 = function (s = this) { var s; s.spaaaaaaace = 4; //type of 'this' in a function expression body is Any @@ -339,17 +312,16 @@ var q1 = function (s) { var t = this; this.spaaaaace = 4; }; -//type of 'this' in a fat arrow expression param list is Any -var q2 = function (s) { - if (s === void 0) { s = _this; } +//type of 'this' in a fat arrow expression param list is typeof globalThis +var q2 = (s = this) => { var s; s.spaaaaaaace = 4; - //type of 'this' in a fat arrow expression body is Any + //type of 'this' in a fat arrow expression body is typeof globalThis var t; - var t = _this; - _this.spaaaaace = 4; + var t = this; + this.spaaaaace = 4; }; -//type of 'this' in global module is Any +//type of 'this' in global module is GlobalThis var t; var t = this; this.spaaaaace = 4; diff --git a/tests/baselines/reference/typeOfThis.symbols b/tests/baselines/reference/typeOfThis.symbols index c89796f8157..11c2ae273c4 100644 --- a/tests/baselines/reference/typeOfThis.symbols +++ b/tests/baselines/reference/typeOfThis.symbols @@ -419,34 +419,42 @@ var q1 = function (s = this) { this.spaaaaace = 4; } -//type of 'this' in a fat arrow expression param list is Any +//type of 'this' in a fat arrow expression param list is typeof globalThis var q2 = (s = this) => { >q2 : Symbol(q2, Decl(typeOfThis.ts, 161, 3)) >s : Symbol(s, Decl(typeOfThis.ts, 161, 10), Decl(typeOfThis.ts, 162, 7)) +>this : Symbol(globalThis) - var s: any; + var s: typeof globalThis; >s : Symbol(s, Decl(typeOfThis.ts, 161, 10), Decl(typeOfThis.ts, 162, 7)) +>globalThis : Symbol(globalThis) s.spaaaaaaace = 4; >s : Symbol(s, Decl(typeOfThis.ts, 161, 10), Decl(typeOfThis.ts, 162, 7)) - //type of 'this' in a fat arrow expression body is Any - var t: any; + //type of 'this' in a fat arrow expression body is typeof globalThis + var t: typeof globalThis; >t : Symbol(t, Decl(typeOfThis.ts, 166, 7), Decl(typeOfThis.ts, 167, 7)) +>globalThis : Symbol(globalThis) var t = this; >t : Symbol(t, Decl(typeOfThis.ts, 166, 7), Decl(typeOfThis.ts, 167, 7)) +>this : Symbol(globalThis) this.spaaaaace = 4; +>this : Symbol(globalThis) } -//type of 'this' in global module is Any -var t: any; +//type of 'this' in global module is GlobalThis +var t: typeof globalThis; >t : Symbol(t, Decl(typeOfThis.ts, 172, 3), Decl(typeOfThis.ts, 173, 3)) +>globalThis : Symbol(globalThis) var t = this; >t : Symbol(t, Decl(typeOfThis.ts, 172, 3), Decl(typeOfThis.ts, 173, 3)) +>this : Symbol(globalThis) this.spaaaaace = 4; +>this : Symbol(globalThis) diff --git a/tests/baselines/reference/typeOfThis.types b/tests/baselines/reference/typeOfThis.types index 0d27690a49a..9f10153eb97 100644 --- a/tests/baselines/reference/typeOfThis.types +++ b/tests/baselines/reference/typeOfThis.types @@ -430,51 +430,54 @@ var q1 = function (s = this) { >4 : 4 } -//type of 'this' in a fat arrow expression param list is Any +//type of 'this' in a fat arrow expression param list is typeof globalThis var q2 = (s = this) => { ->q2 : (s?: any) => void ->(s = this) => { var s: any; s.spaaaaaaace = 4; //type of 'this' in a fat arrow expression body is Any var t: any; var t = this; this.spaaaaace = 4;} : (s?: any) => void ->s : any ->this : any +>q2 : (s?: typeof globalThis) => void +>(s = this) => { var s: typeof globalThis; s.spaaaaaaace = 4; //type of 'this' in a fat arrow expression body is typeof globalThis var t: typeof globalThis; var t = this; this.spaaaaace = 4;} : (s?: typeof globalThis) => void +>s : typeof globalThis +>this : typeof globalThis - var s: any; ->s : any + var s: typeof globalThis; +>s : typeof globalThis +>globalThis : typeof globalThis s.spaaaaaaace = 4; >s.spaaaaaaace = 4 : 4 >s.spaaaaaaace : any ->s : any +>s : typeof globalThis >spaaaaaaace : any >4 : 4 - //type of 'this' in a fat arrow expression body is Any - var t: any; ->t : any + //type of 'this' in a fat arrow expression body is typeof globalThis + var t: typeof globalThis; +>t : typeof globalThis +>globalThis : typeof globalThis var t = this; ->t : any ->this : any +>t : typeof globalThis +>this : typeof globalThis this.spaaaaace = 4; >this.spaaaaace = 4 : 4 >this.spaaaaace : any ->this : any +>this : typeof globalThis >spaaaaace : any >4 : 4 } -//type of 'this' in global module is Any -var t: any; ->t : any +//type of 'this' in global module is GlobalThis +var t: typeof globalThis; +>t : typeof globalThis +>globalThis : typeof globalThis var t = this; ->t : any ->this : any +>t : typeof globalThis +>this : typeof globalThis this.spaaaaace = 4; >this.spaaaaace = 4 : 4 >this.spaaaaace : any ->this : any +>this : typeof globalThis >spaaaaace : any >4 : 4 diff --git a/tests/baselines/reference/unknownSymbols1.symbols b/tests/baselines/reference/unknownSymbols1.symbols index d9726011f1a..c6f67db4a1d 100644 --- a/tests/baselines/reference/unknownSymbols1.symbols +++ b/tests/baselines/reference/unknownSymbols1.symbols @@ -54,6 +54,7 @@ class C4 extends C3 { var x2 = this.asdf; // no error, this is any >x2 : Symbol(x2, Decl(unknownSymbols1.ts, 25, 3)) +>this : Symbol(globalThis) class C5 { >C5 : Symbol(C5, Decl(unknownSymbols1.ts, 25, 19)) diff --git a/tests/baselines/reference/unknownSymbols1.types b/tests/baselines/reference/unknownSymbols1.types index f4532733485..9fced36d703 100644 --- a/tests/baselines/reference/unknownSymbols1.types +++ b/tests/baselines/reference/unknownSymbols1.types @@ -57,7 +57,7 @@ class C4 extends C3 { var x2 = this.asdf; // no error, this is any >x2 : any >this.asdf : any ->this : any +>this : typeof globalThis >asdf : any class C5 { diff --git a/tests/baselines/reference/wrappedIncovations1.symbols b/tests/baselines/reference/wrappedIncovations1.symbols index 49ccc1fa896..09493341040 100644 --- a/tests/baselines/reference/wrappedIncovations1.symbols +++ b/tests/baselines/reference/wrappedIncovations1.symbols @@ -1,6 +1,7 @@ === tests/cases/compiler/wrappedIncovations1.ts === var v = this >v : Symbol(v, Decl(wrappedIncovations1.ts, 0, 3)) +>this : Symbol(globalThis) .foo() .bar() diff --git a/tests/baselines/reference/wrappedIncovations1.types b/tests/baselines/reference/wrappedIncovations1.types index 32f7bb0e1b8..92adf203aa9 100644 --- a/tests/baselines/reference/wrappedIncovations1.types +++ b/tests/baselines/reference/wrappedIncovations1.types @@ -7,7 +7,7 @@ var v = this >this .foo() .bar : any >this .foo() : any >this .foo : any ->this : any +>this : typeof globalThis .foo() >foo : any diff --git a/tests/baselines/reference/wrappedIncovations2.symbols b/tests/baselines/reference/wrappedIncovations2.symbols index 2836bf7c19c..6e5dcf7aae2 100644 --- a/tests/baselines/reference/wrappedIncovations2.symbols +++ b/tests/baselines/reference/wrappedIncovations2.symbols @@ -1,6 +1,7 @@ === tests/cases/compiler/wrappedIncovations2.ts === var v = this. >v : Symbol(v, Decl(wrappedIncovations2.ts, 0, 3)) +>this : Symbol(globalThis) foo(). bar(). diff --git a/tests/baselines/reference/wrappedIncovations2.types b/tests/baselines/reference/wrappedIncovations2.types index 96337796bcd..71317c3f9c2 100644 --- a/tests/baselines/reference/wrappedIncovations2.types +++ b/tests/baselines/reference/wrappedIncovations2.types @@ -7,7 +7,7 @@ var v = this. >this. foo(). bar : any >this. foo() : any >this. foo : any ->this : any +>this : typeof globalThis foo(). >foo : any diff --git a/tests/cases/conformance/es2019/globalThisPropertyAssignment.ts b/tests/cases/conformance/es2019/globalThisPropertyAssignment.ts new file mode 100644 index 00000000000..fb9638e30fb --- /dev/null +++ b/tests/cases/conformance/es2019/globalThisPropertyAssignment.ts @@ -0,0 +1,10 @@ +// @allowJs: true +// @checkJs: true +// @noEmit: true +// @Filename: globalThisPropertyAssignment.js +this.x = 1 +var y = 2 +// should work in JS +window.z = 3 +// should work in JS (even though it's a secondary declaration) +globalThis.alpha = 4 diff --git a/tests/cases/conformance/es2019/globalThisReadonlyProperties.ts b/tests/cases/conformance/es2019/globalThisReadonlyProperties.ts new file mode 100644 index 00000000000..f641fe8d0da --- /dev/null +++ b/tests/cases/conformance/es2019/globalThisReadonlyProperties.ts @@ -0,0 +1,5 @@ +globalThis.globalThis = 1 as any // should error +var x = 1 +const y = 2 +globalThis.x = 3 +globalThis.y = 4 // should error diff --git a/tests/cases/conformance/es2019/globalThisTypeIndexAccess.ts b/tests/cases/conformance/es2019/globalThisTypeIndexAccess.ts new file mode 100644 index 00000000000..88f68f8f884 --- /dev/null +++ b/tests/cases/conformance/es2019/globalThisTypeIndexAccess.ts @@ -0,0 +1,2 @@ + +declare const w_e: (typeof globalThis)["globalThis"] diff --git a/tests/cases/conformance/es2019/globalThisUnknown.ts b/tests/cases/conformance/es2019/globalThisUnknown.ts new file mode 100644 index 00000000000..b1ae4224e1e --- /dev/null +++ b/tests/cases/conformance/es2019/globalThisUnknown.ts @@ -0,0 +1,13 @@ +declare let win: Window & typeof globalThis; + +// this access should be an error +win.hi +// these two should be fine, with type any +this.hi +globalThis.hi + +// element access is always ok without noImplicitAny +win['hi'] +this['hi'] +globalThis['hi'] + diff --git a/tests/cases/conformance/es2019/globalThisUnknownNoImplicitAny.ts b/tests/cases/conformance/es2019/globalThisUnknownNoImplicitAny.ts new file mode 100644 index 00000000000..53fb9a98edb --- /dev/null +++ b/tests/cases/conformance/es2019/globalThisUnknownNoImplicitAny.ts @@ -0,0 +1,11 @@ +// @noImplicitAny: true +declare let win: Window & typeof globalThis; + +// all accesses should be errors +win.hi +this.hi +globalThis.hi + +win['hi'] +this['hi'] +globalThis['hi'] diff --git a/tests/cases/conformance/es2019/globalThisVarDeclaration.ts b/tests/cases/conformance/es2019/globalThisVarDeclaration.ts new file mode 100644 index 00000000000..5b75d1095a6 --- /dev/null +++ b/tests/cases/conformance/es2019/globalThisVarDeclaration.ts @@ -0,0 +1,35 @@ +// @out: output.js +// @target: esnext +// @lib: esnext, dom +// @Filename: b.js +// @allowJs: true +// @checkJs: true +var a = 10; +this.a; +this.b; +globalThis.a; +globalThis.b; + +// DOM access is not supported until the index signature is handled more strictly +self.a; +self.b; +window.a; +window.b; +top.a; +top.b; + +// @Filename: actual.ts +var b = 10; +this.a; +this.b; +globalThis.a; +globalThis.b; + +// same here -- no DOM access to globalThis yet +self.a; +self.b; +window.a; +window.b; +top.a; +top.b; + diff --git a/tests/cases/conformance/expressions/thisKeyword/typeOfThis.ts b/tests/cases/conformance/expressions/thisKeyword/typeOfThis.ts index 4e9da72af6d..3a793f1f391 100644 --- a/tests/cases/conformance/expressions/thisKeyword/typeOfThis.ts +++ b/tests/cases/conformance/expressions/thisKeyword/typeOfThis.ts @@ -1,3 +1,4 @@ +// @target: esnext class MyTestClass { private canary: number; static staticCanary: number; @@ -158,19 +159,19 @@ var q1 = function (s = this) { this.spaaaaace = 4; } -//type of 'this' in a fat arrow expression param list is Any +//type of 'this' in a fat arrow expression param list is typeof globalThis var q2 = (s = this) => { - var s: any; + var s: typeof globalThis; s.spaaaaaaace = 4; - //type of 'this' in a fat arrow expression body is Any - var t: any; + //type of 'this' in a fat arrow expression body is typeof globalThis + var t: typeof globalThis; var t = this; this.spaaaaace = 4; } -//type of 'this' in global module is Any -var t: any; +//type of 'this' in global module is GlobalThis +var t: typeof globalThis; var t = this; this.spaaaaace = 4; diff --git a/tests/cases/conformance/salsa/topLevelThisAssignment.ts b/tests/cases/conformance/salsa/topLevelThisAssignment.ts index 162bed0c30f..aed2f867108 100644 --- a/tests/cases/conformance/salsa/topLevelThisAssignment.ts +++ b/tests/cases/conformance/salsa/topLevelThisAssignment.ts @@ -1,5 +1,6 @@ // @out: output.js // @allowJs: true +// @checkJs: true // @Filename: a.js this.a = 10; this.a; diff --git a/tests/cases/fourslash/completionEntryForClassMembers.ts b/tests/cases/fourslash/completionEntryForClassMembers.ts index 9da74be0bb1..6dcfd059c46 100644 --- a/tests/cases/fourslash/completionEntryForClassMembers.ts +++ b/tests/cases/fourslash/completionEntryForClassMembers.ts @@ -130,6 +130,7 @@ verify.completions( marker: "InsideMethod", exact: [ "arguments", + "globalThis", "B", "C", "D", "D1", "D2", "D3", "D4", "D5", "D6", "E", "F", "F2", "G", "G2", "H", "I", "J", "K", "L", "L2", "M", "N", "O", "undefined", ...completion.insideMethodKeywords, diff --git a/tests/cases/fourslash/completionListIsGlobalCompletion.ts b/tests/cases/fourslash/completionListIsGlobalCompletion.ts index f8ee9430537..2a37849c2b8 100644 --- a/tests/cases/fourslash/completionListIsGlobalCompletion.ts +++ b/tests/cases/fourslash/completionListIsGlobalCompletion.ts @@ -47,6 +47,6 @@ verify.completions( { marker: "10", exact: completion.classElementKeywords, isGlobalCompletion: false, isNewIdentifierLocation: true }, { marker: "13", exact: globals, isGlobalCompletion: false }, { marker: "15", exact: globals, isGlobalCompletion: true, isNewIdentifierLocation: true }, - { marker: "16", exact: [...x, ...completion.globalsVars, "undefined"], isGlobalCompletion: false }, + { marker: "16", exact: [...x, "globalThis", ...completion.globalsVars, "undefined"], isGlobalCompletion: false }, { marker: "17", exact: completion.globalKeywordsPlusUndefined, isGlobalCompletion: false }, ); diff --git a/tests/cases/fourslash/completionListKeywords.ts b/tests/cases/fourslash/completionListKeywords.ts index 660099d3188..ed489487b3c 100644 --- a/tests/cases/fourslash/completionListKeywords.ts +++ b/tests/cases/fourslash/completionListKeywords.ts @@ -4,4 +4,4 @@ /////**/ -verify.completions({ marker: "", exact: ["undefined", ...completion.statementKeywordsWithTypes] }); +verify.completions({ marker: "", exact: ["globalThis", "undefined", ...completion.statementKeywordsWithTypes] }); diff --git a/tests/cases/fourslash/completionListWithMeanings.ts b/tests/cases/fourslash/completionListWithMeanings.ts index 8c3498ebda5..41df1ed3816 100644 --- a/tests/cases/fourslash/completionListWithMeanings.ts +++ b/tests/cases/fourslash/completionListWithMeanings.ts @@ -16,6 +16,7 @@ ////var zz = { x: 4, y: 3 }; const values: ReadonlyArray = [ + "globalThis", { name: "m2", text: "namespace m2" }, // With no type side, allowed only in value { name: "m3", text: "namespace m3" }, { name: "xx", text: "var xx: number" }, @@ -28,6 +29,7 @@ const values: ReadonlyArray = [ ]; const types: ReadonlyArray = [ + "globalThis", { name: "m", text: "namespace m" }, { name: "m3", text: "namespace m3" }, { name: "point", text: "interface point" }, diff --git a/tests/cases/fourslash/completionListWithModulesFromModule.ts b/tests/cases/fourslash/completionListWithModulesFromModule.ts index d08e26a8d50..dbcbdd79783 100644 --- a/tests/cases/fourslash/completionListWithModulesFromModule.ts +++ b/tests/cases/fourslash/completionListWithModulesFromModule.ts @@ -263,6 +263,7 @@ verify.completions( { name: "shwvar", text: "var shwvar: string" }, { name: "shwcls", text: "class shwcls" }, "tmp", + "globalThis", ...commonValues, "undefined", ...completion.statementKeywordsWithTypes, @@ -272,6 +273,7 @@ verify.completions( exact: [ { name: "shwcls", text: "class shwcls" }, { name: "shwint", text: "interface shwint" }, + "globalThis", ...commonTypes, ...completion.typeKeywords, ] @@ -282,6 +284,7 @@ verify.completions( "Mod1", "iMod1", "tmp", + "globalThis", { name: "shwfn", text: "function shwfn(): void" }, ...commonValues, { name: "shwcls", text: "class shwcls" }, @@ -295,6 +298,7 @@ verify.completions( exact: [ "Mod1", "iMod1", + "globalThis", ...commonTypes, { name: "shwcls", text: "class shwcls" }, { name: "shwint", text: "interface shwint" }, diff --git a/tests/cases/fourslash/completionsImport_default_anonymous.ts b/tests/cases/fourslash/completionsImport_default_anonymous.ts index 8aa9dfb5af6..720bb3f1c6b 100644 --- a/tests/cases/fourslash/completionsImport_default_anonymous.ts +++ b/tests/cases/fourslash/completionsImport_default_anonymous.ts @@ -14,7 +14,7 @@ goTo.marker("0"); const preferences: FourSlashInterface.UserPreferences = { includeCompletionsForModuleExports: true }; verify.completions( - { marker: "0", exact: ["undefined", ...completion.statementKeywordsWithTypes], preferences }, + { marker: "0", exact: ["globalThis", "undefined", ...completion.statementKeywordsWithTypes], preferences }, { marker: "1", includes: { name: "fooBar", source: "/src/foo-bar", sourceDisplay: "./foo-bar", text: "(property) default: 0", kind: "property", hasAction: true }, diff --git a/tests/cases/fourslash/completionsImport_exportEquals_anonymous.ts b/tests/cases/fourslash/completionsImport_exportEquals_anonymous.ts index c5e87877cfb..8fc73457117 100644 --- a/tests/cases/fourslash/completionsImport_exportEquals_anonymous.ts +++ b/tests/cases/fourslash/completionsImport_exportEquals_anonymous.ts @@ -14,7 +14,7 @@ goTo.marker("0"); const preferences: FourSlashInterface.UserPreferences = { includeCompletionsForModuleExports: true }; const exportEntry: FourSlashInterface.ExpectedCompletionEntryObject = { name: "fooBar", source: "/src/foo-bar", sourceDisplay: "./foo-bar", text: "(property) export=: 0", kind: "property", hasAction: true }; verify.completions( - { marker: "0", exact: ["undefined", exportEntry, ...completion.statementKeywordsWithTypes], preferences }, + { marker: "0", exact: ["globalThis", "undefined", exportEntry, ...completion.statementKeywordsWithTypes], preferences }, { marker: "1", includes: exportEntry, preferences } ); verify.applyCodeActionFromCompletion("0", { @@ -25,4 +25,4 @@ verify.applyCodeActionFromCompletion("0", { exp fooB`, -}); \ No newline at end of file +}); diff --git a/tests/cases/fourslash/completionsImport_keywords.ts b/tests/cases/fourslash/completionsImport_keywords.ts index 6d4edd83b36..64bab64c7a8 100644 --- a/tests/cases/fourslash/completionsImport_keywords.ts +++ b/tests/cases/fourslash/completionsImport_keywords.ts @@ -34,7 +34,7 @@ verify.completions( { marker: "unique", exact: [ - ...completion.globalsVars, "undefined", + "globalThis", ...completion.globalsVars, "undefined", { name: "unique", source: "/a", sourceDisplay: "./a", text: "(alias) const unique: 0\nexport unique", hasAction: true }, ...completion.globalKeywords.filter(e => e.name !== "unique"), ], diff --git a/tests/cases/fourslash/completionsImport_multipleWithSameName.ts b/tests/cases/fourslash/completionsImport_multipleWithSameName.ts index ae552f437fe..5893f6f0fdc 100644 --- a/tests/cases/fourslash/completionsImport_multipleWithSameName.ts +++ b/tests/cases/fourslash/completionsImport_multipleWithSameName.ts @@ -20,6 +20,7 @@ goTo.marker(""); verify.completions({ marker: "", exact: [ + "globalThis", { name: "foo", text: "var foo: number", kind: "var", kindModifiers: "declare" }, "undefined", { diff --git a/tests/cases/fourslash/completionsImport_named_didNotExistBefore.ts b/tests/cases/fourslash/completionsImport_named_didNotExistBefore.ts index 10a0c124e4d..5f21db1e376 100644 --- a/tests/cases/fourslash/completionsImport_named_didNotExistBefore.ts +++ b/tests/cases/fourslash/completionsImport_named_didNotExistBefore.ts @@ -14,6 +14,7 @@ verify.completions({ marker: "", exact: [ { name: "Test2", text: "(alias) function Test2(): void\nimport Test2", kind: "alias" }, + "globalThis", "undefined", { name: "Test1", source: "/a", sourceDisplay: "./a", text: "function Test1(): void", kind: "function", kindModifiers: "export", hasAction: true }, ...completion.statementKeywordsWithTypes, diff --git a/tests/cases/fourslash/completionsImport_ofAlias_preferShortPath.ts b/tests/cases/fourslash/completionsImport_ofAlias_preferShortPath.ts index f5efa9cd912..71242bc240a 100644 --- a/tests/cases/fourslash/completionsImport_ofAlias_preferShortPath.ts +++ b/tests/cases/fourslash/completionsImport_ofAlias_preferShortPath.ts @@ -19,6 +19,7 @@ verify.completions({ marker: "", exact: [ + "globalThis", "undefined", { name: "foo", source: "/foo/lib/foo", sourceDisplay: "./foo", text: "const foo: 0", kind: "const", kindModifiers: "export", hasAction: true }, ...completion.statementKeywordsWithTypes, diff --git a/tests/cases/fourslash/completionsImport_reExportDefault.ts b/tests/cases/fourslash/completionsImport_reExportDefault.ts index 8e38faa0b05..7f6639c3f13 100644 --- a/tests/cases/fourslash/completionsImport_reExportDefault.ts +++ b/tests/cases/fourslash/completionsImport_reExportDefault.ts @@ -15,6 +15,7 @@ verify.completions({ marker: "", exact: [ + "globalThis", ...completion.globalsVars, "undefined", { diff --git a/tests/cases/fourslash/completionsImport_shadowedByLocal.ts b/tests/cases/fourslash/completionsImport_shadowedByLocal.ts index afe88fa6da8..711386816c0 100644 --- a/tests/cases/fourslash/completionsImport_shadowedByLocal.ts +++ b/tests/cases/fourslash/completionsImport_shadowedByLocal.ts @@ -11,6 +11,6 @@ verify.completions({ marker: "", - exact: [{ name: "foo", text: "const foo: 1" }, "undefined", ...completion.statementKeywordsWithTypes], + exact: ["globalThis", { name: "foo", text: "const foo: 1" }, "undefined", ...completion.statementKeywordsWithTypes], preferences: { includeCompletionsForModuleExports: true }, }); diff --git a/tests/cases/fourslash/completionsTypeKeywords.ts b/tests/cases/fourslash/completionsTypeKeywords.ts index 10a6d453759..4c26e13932e 100644 --- a/tests/cases/fourslash/completionsTypeKeywords.ts +++ b/tests/cases/fourslash/completionsTypeKeywords.ts @@ -6,5 +6,5 @@ verify.completions({ marker: "", - exact: ["T", ...completion.typeKeywords], + exact: ["globalThis", "T", ...completion.typeKeywords], }); diff --git a/tests/cases/fourslash/findAllRefsThisKeyword.ts b/tests/cases/fourslash/findAllRefsThisKeyword.ts index 34995467a27..b0045e91bc1 100644 --- a/tests/cases/fourslash/findAllRefsThisKeyword.ts +++ b/tests/cases/fourslash/findAllRefsThisKeyword.ts @@ -24,8 +24,8 @@ ////const x = { [|{| "isWriteAccess": true, "isDefinition": true |}this|]: 0 } ////x.[|this|]; -const [global, f0, f1, g0, g1, x, y, constructor, method, propDef, propUse] = test.ranges(); -verify.singleReferenceGroup("this", [global]); +const [glob, f0, f1, g0, g1, x, y, constructor, method, propDef, propUse] = test.ranges(); +verify.singleReferenceGroup("this: typeof globalThis", [glob]); verify.singleReferenceGroup("(parameter) this: any", [f0, f1]); verify.singleReferenceGroup("(parameter) this: any", [g0, g1]); verify.singleReferenceGroup("this: typeof C", [x, y]); diff --git a/tests/cases/fourslash/findAllRefsThisKeywordMultipleFiles.ts b/tests/cases/fourslash/findAllRefsThisKeywordMultipleFiles.ts index d94f2993d1d..807bc9bf194 100644 --- a/tests/cases/fourslash/findAllRefsThisKeywordMultipleFiles.ts +++ b/tests/cases/fourslash/findAllRefsThisKeywordMultipleFiles.ts @@ -12,4 +12,4 @@ //// // different 'this' //// function f(this) { return this; } -verify.singleReferenceGroup("this"); +verify.singleReferenceGroup("this: typeof globalThis"); diff --git a/tests/cases/fourslash/tsxCompletionOnOpeningTagWithoutJSX1.ts b/tests/cases/fourslash/tsxCompletionOnOpeningTagWithoutJSX1.ts index 7a577cfbcce..9198f5a857a 100644 --- a/tests/cases/fourslash/tsxCompletionOnOpeningTagWithoutJSX1.ts +++ b/tests/cases/fourslash/tsxCompletionOnOpeningTagWithoutJSX1.ts @@ -3,4 +3,4 @@ //@Filename: file.tsx //// var x = Date: Wed, 27 Feb 2019 14:33:25 -0800 Subject: [PATCH 128/149] Don't crash if someone created a folder while we were checking to see if it exists --- src/compiler/sys.ts | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts index 33283c93803..6d8c4628092 100644 --- a/src/compiler/sys.ts +++ b/src/compiler/sys.ts @@ -615,7 +615,17 @@ namespace ts { directoryExists, createDirectory(directoryName: string) { if (!nodeSystem.directoryExists(directoryName)) { - _fs.mkdirSync(directoryName); + // Wrapped in a try-catch to prevent crashing if we are in a race + // with another copy of ourselves to create the same directory + try { + _fs.mkdirSync(directoryName); + } + catch (e) { + if (e.code !== "EEXIST") { + // Failed for some other reason (access denied?); still throw + throw e; + } + } } }, getExecutingFilePath() { From 54c7996ff511e7a95c2184111abe7c611041780f Mon Sep 17 00:00:00 2001 From: Gabriela Araujo Britto Date: Wed, 27 Feb 2019 16:19:01 -0800 Subject: [PATCH 129/149] refactor getGroupReferences --- .../refactors/convertToNamedParameters.ts | 170 +++++++++--------- src/services/utilities.ts | 12 ++ 2 files changed, 96 insertions(+), 86 deletions(-) diff --git a/src/services/refactors/convertToNamedParameters.ts b/src/services/refactors/convertToNamedParameters.ts index fa285619dab..f0873a56baf 100644 --- a/src/services/refactors/convertToNamedParameters.ts +++ b/src/services/refactors/convertToNamedParameters.ts @@ -4,14 +4,14 @@ namespace ts.refactor.convertToNamedParameters { const refactorDescription = "Convert to named parameters"; const actionNameNamedParameters = "Convert to named parameters"; const actionDescriptionNamedParameters = "Convert to named parameters"; - const minimumParameterLength = 1; + const minimumParameterLength = 2; registerRefactor(refactorName, { getEditsForAction, getAvailableActions }); function getAvailableActions(context: RefactorContext): ReadonlyArray { const { file, startPosition } = context; const isJSFile = isSourceFileJS(file); - if (isJSFile) return emptyArray; + if (isJSFile) return emptyArray; // TODO: GH#30113 const functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, context.program.getTypeChecker()); if (!functionDeclaration) return emptyArray; @@ -37,7 +37,7 @@ namespace ts.refactor.convertToNamedParameters { return { renameFilename: undefined, renameLocation: undefined, edits }; } - return { edits: [] }; + return { edits: [] }; // TODO: GH#30113 } function doChange(sourceFile: SourceFile, program: Program, host: LanguageServiceHost, changes: textChanges.ChangeTracker, functionDeclaration: ValidFunctionDeclaration, groupedReferences: GroupedReferences): void { @@ -55,7 +55,7 @@ namespace ts.refactor.convertToNamedParameters { }); - const functionCalls = deduplicate(groupedReferences.functionCalls, (a, b) => a === b); + const functionCalls = deduplicate(groupedReferences.functionCalls, equateValues); forEach(functionCalls, call => { if (call.arguments && call.arguments.length) { const newArgument = getSynthesizedDeepClone(createNewArgument(functionDeclaration, call.arguments), /*includeTrivia*/ true); @@ -69,60 +69,57 @@ namespace ts.refactor.convertToNamedParameters { } function getGroupedReferences(functionDeclaration: ValidFunctionDeclaration, program: Program, cancellationToken: CancellationToken): GroupedReferences { - const names = getDeclarationNames(functionDeclaration); - const references = flatMap(names, name => FindAllReferences.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken)); - let groupedReferences = groupReferences(references); + const functionNames = getFunctionNames(functionDeclaration); + const classNames = isConstructorDeclaration(functionDeclaration) ? getClassNames(functionDeclaration) : []; + const names = deduplicate([...functionNames, ...classNames], equateValues); + const checker = program.getTypeChecker(); - // if the refactored function is a constructor, we must also go through the references to its class - if (isConstructorDeclaration(functionDeclaration)) { - const className = getClassName(functionDeclaration); - groupedReferences = groupClassReferences(groupedReferences, className); + const references = flatMap(names, name => FindAllReferences.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken)); + const isConstructor = isConstructorDeclaration(functionDeclaration); + const groupedReferences = groupReferences(references, isConstructor); + + if (!every(groupedReferences.declarations, decl => contains(names, decl))) { + groupedReferences.valid = false; } - validateReferences(groupedReferences); return groupedReferences; - function getClassName(constructorDeclaration: ValidConstructor): Identifier { - switch (constructorDeclaration.parent.kind) { - case SyntaxKind.ClassDeclaration: - return constructorDeclaration.parent.name; - case SyntaxKind.ClassExpression: - return constructorDeclaration.parent.parent.name; - } - } - - function groupReferences(referenceEntries: ReadonlyArray | undefined): GroupedReferences { - const groupedReferences: GroupedReferences = { functionCalls: [], declarations: [], unhandled: [], valid: true }; - - forEach(referenceEntries, (entry) => { - const decl = entryToDeclaration(entry); - if (decl) { - groupedReferences.declarations.push(decl); - return; - } - - const call = entryToFunctionCall(entry); - if (call) { - groupedReferences.functionCalls.push(call); - return; - } - - groupedReferences.unhandled.push(entry); - }); - return groupedReferences; - } - - function groupClassReferences(groupedReferences: GroupedReferences, className: Identifier): GroupedReferences { + function groupReferences(referenceEntries: ReadonlyArray, isConstructor: boolean): GroupedReferences { const classReferences: ClassReferences = { accessExpressions: [], typeUsages: [] }; - const unhandledEntries = groupedReferences.unhandled; - const newUnhandledEntries: FindAllReferences.Entry[] = []; + const groupedReferences: GroupedReferences = { functionCalls: [], declarations: [], classReferences, valid: true }; + const functionSymbols = map(functionNames, checker.getSymbolAtLocation); + const classSymbols = map(classNames, checker.getSymbolAtLocation); + + for (const entry of referenceEntries) { + if (entry.kind !== FindAllReferences.EntryKind.Node) { + groupedReferences.valid = false; + continue; + } + if (contains(functionSymbols, checker.getSymbolAtLocation(entry.node), symbolComparer)) { + const decl = entryToDeclaration(entry); + if (decl) { + groupedReferences.declarations.push(decl); + continue; + } + + const call = entryToFunctionCall(entry); + if (call) { + groupedReferences.functionCalls.push(call); + continue; + } + } + // if the refactored function is a constructor, we must also check if the references to its class are valid + if (isConstructor && contains(classSymbols, checker.getSymbolAtLocation(entry.node), symbolComparer)) { + const decl = entryToDeclaration(entry); + if (decl) { + groupedReferences.declarations.push(decl); + continue; + } - forEach(unhandledEntries, (entry) => { - if (entry.kind === FindAllReferences.EntryKind.Node && entry.node.symbol === className.symbol) { const accessExpression = entryToAccessExpression(entry); if (accessExpression) { classReferences.accessExpressions.push(accessExpression); - return; + continue; } // Only class declarations are allowed to be used as a type (in a heritage clause), @@ -131,27 +128,29 @@ namespace ts.refactor.convertToNamedParameters { const type = entryToType(entry); if (type) { classReferences.typeUsages.push(type); - return; + continue; } } } - newUnhandledEntries.push(entry); - }); - - return { ...groupedReferences, classReferences, unhandled: newUnhandledEntries }; - } - - function validateReferences(groupedReferences: GroupedReferences): void { - if (groupedReferences.unhandled.length > 0) { - groupedReferences.valid = false; - } - if (!every(groupedReferences.declarations, decl => contains(names, decl))) { groupedReferences.valid = false; } + + return groupedReferences; } - function entryToFunctionCall(entry: FindAllReferences.Entry): CallExpression | NewExpression | undefined { - if (entry.kind === FindAllReferences.EntryKind.Node && entry.node.parent) { + function symbolComparer(a: Symbol, b: Symbol): boolean { + return getSymbolTarget(a) === getSymbolTarget(b); + } + + function entryToDeclaration(entry: FindAllReferences.NodeEntry): Node | undefined { + if (isDeclaration(entry.node.parent)) { + return entry.node; + } + return undefined; + } + + function entryToFunctionCall(entry: FindAllReferences.NodeEntry): CallExpression | NewExpression | undefined { + if (entry.node.parent) { const functionReference = entry.node; const parent = functionReference.parent; switch (parent.kind) { @@ -194,15 +193,8 @@ namespace ts.refactor.convertToNamedParameters { return undefined; } - function entryToDeclaration(entry: FindAllReferences.Entry): Node | undefined { - if (entry.kind === FindAllReferences.EntryKind.Node && contains(names, entry.node)) { - return entry.node; - } - return undefined; - } - - function entryToAccessExpression(entry: FindAllReferences.Entry): ElementAccessExpression | PropertyAccessExpression | undefined { - if (entry.kind === FindAllReferences.EntryKind.Node && entry.node.parent) { + function entryToAccessExpression(entry: FindAllReferences.NodeEntry): ElementAccessExpression | PropertyAccessExpression | undefined { + if (entry.node.parent) { const reference = entry.node; const parent = reference.parent; switch (parent.kind) { @@ -263,7 +255,7 @@ namespace ts.refactor.convertToNamedParameters { return false; function isValidParameterNodeArray(parameters: NodeArray): parameters is ValidParameterNodeArray { - return getRefactorableParametersLength(parameters) > minimumParameterLength && every(parameters, isValidParameterDeclaration); + return getRefactorableParametersLength(parameters) >= minimumParameterLength && every(parameters, isValidParameterDeclaration); } function isValidParameterDeclaration(paramDeclaration: ParameterDeclaration): paramDeclaration is ValidParameterDeclaration { @@ -271,7 +263,7 @@ namespace ts.refactor.convertToNamedParameters { } function isValidVariableDeclaration(node: Node): node is ValidVariableDeclaration { - return isVariableDeclaration(node) && isVarConst(node) && isIdentifier(node.name) && !node.type; + return isVariableDeclaration(node) && isVarConst(node) && isIdentifier(node.name) && !node.type; // TODO: GH#30113 } } @@ -430,25 +422,32 @@ namespace ts.refactor.convertToNamedParameters { return getTextOfIdentifierOrLiteral(paramDeclaration.name); } - function getDeclarationNames(functionDeclaration: ValidFunctionDeclaration): Node[] { + function getClassNames(constructorDeclaration: ValidConstructor): Identifier[] { + switch (constructorDeclaration.parent.kind) { + case SyntaxKind.ClassDeclaration: + const classDeclaration = constructorDeclaration.parent; + return [classDeclaration.name]; + case SyntaxKind.ClassExpression: + const classExpression = constructorDeclaration.parent; + const variableDeclaration = constructorDeclaration.parent.parent; + const className = classExpression.name; + if (className) return [className, variableDeclaration.name]; + return [variableDeclaration.name]; + } + } + + function getFunctionNames(functionDeclaration: ValidFunctionDeclaration): Node[] { switch (functionDeclaration.kind) { case SyntaxKind.FunctionDeclaration: case SyntaxKind.MethodDeclaration: return [functionDeclaration.name]; case SyntaxKind.Constructor: const ctrKeyword = findChildOfKind(functionDeclaration, SyntaxKind.ConstructorKeyword, functionDeclaration.getSourceFile())!; - switch (functionDeclaration.parent.kind) { - case SyntaxKind.ClassDeclaration: - const classDeclaration = functionDeclaration.parent; - return [classDeclaration.name, ctrKeyword]; - case SyntaxKind.ClassExpression: - const classExpression = functionDeclaration.parent; - const variableDeclaration = functionDeclaration.parent.parent; - const className = classExpression.name; - if (className) return [className, ctrKeyword, variableDeclaration.name]; - return [ctrKeyword, variableDeclaration.name]; - default: return Debug.assertNever(functionDeclaration.parent); + if (functionDeclaration.parent.kind === SyntaxKind.ClassExpression) { + const variableDeclaration = functionDeclaration.parent.parent; + return [variableDeclaration.name, ctrKeyword]; } + return [ctrKeyword]; case SyntaxKind.ArrowFunction: return [functionDeclaration.parent.name]; case SyntaxKind.FunctionExpression: @@ -500,7 +499,6 @@ namespace ts.refactor.convertToNamedParameters { functionCalls: (CallExpression | NewExpression)[]; declarations: Node[]; classReferences?: ClassReferences; - unhandled: FindAllReferences.Entry[]; valid: boolean; } interface ClassReferences { diff --git a/src/services/utilities.ts b/src/services/utilities.ts index afa14f62a1d..004135a526e 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -1664,6 +1664,18 @@ namespace ts { return ensureScriptKind(fileName, host && host.getScriptKind && host.getScriptKind(fileName)); } + export function getSymbolTarget(symbol: Symbol): Symbol { + let next: Symbol = symbol; + while (isTransientSymbol(next) && next.target) { + next = next.target; + } + return next; + } + + function isTransientSymbol(symbol: Symbol): symbol is TransientSymbol { + return (symbol.flags & SymbolFlags.Transient) !== 0; + } + export function getUniqueSymbolId(symbol: Symbol, checker: TypeChecker) { return getSymbolId(skipAlias(symbol, checker)); } From 7fd6868f8bc59616125d9a2a1453ba7328b23b24 Mon Sep 17 00:00:00 2001 From: Gabriela Araujo Britto Date: Wed, 27 Feb 2019 16:42:54 -0800 Subject: [PATCH 130/149] minor refactors to convertToNamedParameters --- .../refactors/convertToNamedParameters.ts | 29 ++++++++++++++----- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/src/services/refactors/convertToNamedParameters.ts b/src/services/refactors/convertToNamedParameters.ts index f0873a56baf..102001a46a8 100644 --- a/src/services/refactors/convertToNamedParameters.ts +++ b/src/services/refactors/convertToNamedParameters.ts @@ -40,7 +40,13 @@ namespace ts.refactor.convertToNamedParameters { return { edits: [] }; // TODO: GH#30113 } - function doChange(sourceFile: SourceFile, program: Program, host: LanguageServiceHost, changes: textChanges.ChangeTracker, functionDeclaration: ValidFunctionDeclaration, groupedReferences: GroupedReferences): void { + function doChange( + sourceFile: SourceFile, + program: Program, + host: LanguageServiceHost, + changes: textChanges.ChangeTracker, + functionDeclaration: ValidFunctionDeclaration, + groupedReferences: GroupedReferences): void { const newParamDeclaration = map(createNewParameters(functionDeclaration, program, host), param => getSynthesizedDeepClone(param)); changes.replaceNodeRangeWithNodes( sourceFile, @@ -74,7 +80,7 @@ namespace ts.refactor.convertToNamedParameters { const names = deduplicate([...functionNames, ...classNames], equateValues); const checker = program.getTypeChecker(); - const references = flatMap(names, name => FindAllReferences.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken)); + const references = flatMap(names, /*mapfn*/ name => FindAllReferences.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken)); const isConstructor = isConstructorDeclaration(functionDeclaration); const groupedReferences = groupReferences(references, isConstructor); @@ -231,8 +237,12 @@ namespace ts.refactor.convertToNamedParameters { function getFunctionDeclarationAtPosition(file: SourceFile, startPosition: number, checker: TypeChecker): ValidFunctionDeclaration | undefined { const node = getTokenAtPosition(file, startPosition); const functionDeclaration = getContainingFunction(node); - if (!functionDeclaration || !isValidFunctionDeclaration(functionDeclaration, checker) || !rangeContainsRange(functionDeclaration, node) || (functionDeclaration.body && rangeContainsRange(functionDeclaration.body, node))) return undefined; - return functionDeclaration; + if (functionDeclaration + && isValidFunctionDeclaration(functionDeclaration, checker) + && rangeContainsRange(functionDeclaration, node) + && !(functionDeclaration.body && rangeContainsRange(functionDeclaration.body, node))) return functionDeclaration; + + return undefined; } function isValidFunctionDeclaration(functionDeclaration: SignatureDeclaration, checker: TypeChecker): functionDeclaration is ValidFunctionDeclaration { @@ -311,10 +321,11 @@ namespace ts.refactor.convertToNamedParameters { const bindingElements = map(refactorableParameters, createBindingElementFromParameterDeclaration); const objectParameterName = createObjectBindingPattern(bindingElements); const objectParameterType = createParameterTypeNode(refactorableParameters); + const checker = program.getTypeChecker(); let objectInitializer: Expression | undefined; // If every parameter in the original function was optional, add an empty object initializer to the new object parameter - if (every(refactorableParameters, param => !!param.initializer || !!param.questionToken)) { + if (every(refactorableParameters, checker.isOptionalParameter)) { objectInitializer = createObjectLiteral(); } @@ -339,9 +350,9 @@ namespace ts.refactor.convertToNamedParameters { suppressLeadingAndTrailingTrivia(newThisParameter.name); copyComments(thisParameter.name, newThisParameter.name); - if (thisParameter.type && newThisParameter.type) { - suppressLeadingAndTrailingTrivia(newThisParameter.type); - copyComments(thisParameter.type, newThisParameter.type); + if (thisParameter.type) { + suppressLeadingAndTrailingTrivia(newThisParameter.type!); + copyComments(thisParameter.type, newThisParameter.type!); } return createNodeArray([newThisParameter, objectParameter]); @@ -453,6 +464,8 @@ namespace ts.refactor.convertToNamedParameters { case SyntaxKind.FunctionExpression: if (functionDeclaration.name) return [functionDeclaration.name, functionDeclaration.parent.name]; return [functionDeclaration.parent.name]; + default: + return Debug.assertNever(functionDeclaration); } } From 51616a4043bf64a745de1d1e53ca2c6322d58660 Mon Sep 17 00:00:00 2001 From: Gabriela Araujo Britto Date: Thu, 28 Feb 2019 09:50:57 -0800 Subject: [PATCH 131/149] use sortAndDeduplicate instead of deduplicate --- src/services/refactors/convertToNamedParameters.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/services/refactors/convertToNamedParameters.ts b/src/services/refactors/convertToNamedParameters.ts index 102001a46a8..85073dbc76c 100644 --- a/src/services/refactors/convertToNamedParameters.ts +++ b/src/services/refactors/convertToNamedParameters.ts @@ -60,9 +60,8 @@ namespace ts.refactor.convertToNamedParameters { trailingTriviaOption: textChanges.TrailingTriviaOption.Include }); - - const functionCalls = deduplicate(groupedReferences.functionCalls, equateValues); - forEach(functionCalls, call => { + const functionCalls = sortAndDeduplicate(groupedReferences.functionCalls, /*comparer*/ (a, b) => compareValues(a.pos, b.pos)); + for (const call of functionCalls) { if (call.arguments && call.arguments.length) { const newArgument = getSynthesizedDeepClone(createNewArgument(functionDeclaration, call.arguments), /*includeTrivia*/ true); changes.replaceNodeRange( @@ -71,7 +70,8 @@ namespace ts.refactor.convertToNamedParameters { last(call.arguments), newArgument, { leadingTriviaOption: textChanges.LeadingTriviaOption.IncludeAll, trailingTriviaOption: textChanges.TrailingTriviaOption.Include }); - }}); + } + } } function getGroupedReferences(functionDeclaration: ValidFunctionDeclaration, program: Program, cancellationToken: CancellationToken): GroupedReferences { From 617d5af67e9e6db28c0811667db20390864ac483 Mon Sep 17 00:00:00 2001 From: Gabriela Araujo Britto Date: Thu, 28 Feb 2019 11:22:05 -0800 Subject: [PATCH 132/149] add diagnostics message for refactor description --- src/compiler/diagnosticMessages.json | 4 ++++ src/services/refactors/convertToNamedParameters.ts | 13 ++++++------- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 09b0f721292..3a7c59aacfc 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -4871,5 +4871,9 @@ "Enable the 'experimentalDecorators' option in your configuration file": { "category": "Message", "code": 95074 + }, + "Convert to named parameters": { + "category": "Message", + "code": 95075 } } diff --git a/src/services/refactors/convertToNamedParameters.ts b/src/services/refactors/convertToNamedParameters.ts index 85073dbc76c..bd87aba2ead 100644 --- a/src/services/refactors/convertToNamedParameters.ts +++ b/src/services/refactors/convertToNamedParameters.ts @@ -1,9 +1,6 @@ /* @internal */ namespace ts.refactor.convertToNamedParameters { const refactorName = "Convert to named parameters"; - const refactorDescription = "Convert to named parameters"; - const actionNameNamedParameters = "Convert to named parameters"; - const actionDescriptionNamedParameters = "Convert to named parameters"; const minimumParameterLength = 2; registerRefactor(refactorName, { getEditsForAction, getAvailableActions }); @@ -15,18 +12,20 @@ namespace ts.refactor.convertToNamedParameters { const functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, context.program.getTypeChecker()); if (!functionDeclaration) return emptyArray; + const description = getLocaleSpecificMessage(Diagnostics.Convert_to_named_parameters); return [{ name: refactorName, - description: refactorDescription, + description, + inlineable: false, actions: [{ - name: actionNameNamedParameters, - description: actionDescriptionNamedParameters + name: refactorName, + description }] }]; } function getEditsForAction(context: RefactorContext, actionName: string): RefactorEditInfo | undefined { - Debug.assert(actionName === actionNameNamedParameters); + Debug.assert(actionName === refactorName); const { file, startPosition, program, cancellationToken, host } = context; const functionDeclaration = getFunctionDeclarationAtPosition(file, startPosition, program.getTypeChecker()); if (!functionDeclaration || !cancellationToken) return undefined; From a6a3ae00a614ec76272ed101557a5ea121cd81f5 Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Thu, 28 Feb 2019 12:46:24 -0800 Subject: [PATCH 133/149] Only collect inferences which actually have inferences into the returnMapper (#30111) --- src/compiler/checker.ts | 21 +++++- .../returnTypeInferenceNotTooBroad.js | 24 +++++++ .../returnTypeInferenceNotTooBroad.symbols | 67 +++++++++++++++++++ .../returnTypeInferenceNotTooBroad.types | 65 ++++++++++++++++++ .../returnTypeInferenceNotTooBroad.ts | 14 ++++ 5 files changed, 189 insertions(+), 2 deletions(-) create mode 100644 tests/baselines/reference/returnTypeInferenceNotTooBroad.js create mode 100644 tests/baselines/reference/returnTypeInferenceNotTooBroad.symbols create mode 100644 tests/baselines/reference/returnTypeInferenceNotTooBroad.types create mode 100644 tests/cases/compiler/returnTypeInferenceNotTooBroad.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index cf61c4a97a8..363eeca7894 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -10691,6 +10691,23 @@ namespace ts { mapper; } + function cloneInferredPartOfContext(context: InferenceContext): InferenceContext | undefined { + // Filter context to only those parameters which actually have inference candidates + const params = []; + const inferences = []; + for (let i = 0; i < context.typeParameters.length; i++) { + const info = context.inferences[i]; + if (info.candidates || info.contraCandidates) { + params.push(context.typeParameters[i]); + inferences.push(info); + } + } + if (!params.length) { + return undefined; + } + return createInferenceContext(params, context.signature, context.flags | InferenceFlags.NoDefault, context.compareTypes, inferences); + } + function combineTypeMappers(mapper1: TypeMapper | undefined, mapper2: TypeMapper): TypeMapper; function combineTypeMappers(mapper1: TypeMapper, mapper2: TypeMapper | undefined): TypeMapper; function combineTypeMappers(mapper1: TypeMapper, mapper2: TypeMapper): TypeMapper { @@ -14900,7 +14917,7 @@ namespace ts { // parameter should be instantiated to the empty object type. inferredType = instantiateType(defaultType, combineTypeMappers( - createBackreferenceMapper(context.signature!.typeParameters!, index), + createBackreferenceMapper(context.typeParameters, index), context)); } else { @@ -20069,7 +20086,7 @@ namespace ts { inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, InferencePriority.ReturnType); // Create a type mapper for instantiating generic contextual types using the inferences made // from the return type. - context.returnMapper = cloneTypeMapper(context); + context.returnMapper = cloneInferredPartOfContext(context); } } diff --git a/tests/baselines/reference/returnTypeInferenceNotTooBroad.js b/tests/baselines/reference/returnTypeInferenceNotTooBroad.js new file mode 100644 index 00000000000..74ee34f508b --- /dev/null +++ b/tests/baselines/reference/returnTypeInferenceNotTooBroad.js @@ -0,0 +1,24 @@ +//// [returnTypeInferenceNotTooBroad.ts] +type Signs = { kind: 'a'; a: 3; } | { kind: 'b'; b: 2; } | { kind: 'c'; c: 1; }; +interface Opts { + low?: number; + sign?: T +} +interface Wrapper { +} +declare function sepsis(opts: Opts): Wrapper; +declare function unwrap(w: Wrapper): T; +export const y = sepsis({ low: 1, sign: { kind: 'a', a: 3 }}); +// $ExpectType { kind: "a"; a: 3; } +export const yun = unwrap(y); +// $ExpectType { kind: "a"; a: 3; } +export const yone = unwrap(sepsis({ low: 1, sign: { kind: 'a', a: 3 }})); + +//// [returnTypeInferenceNotTooBroad.js] +"use strict"; +exports.__esModule = true; +exports.y = sepsis({ low: 1, sign: { kind: 'a', a: 3 } }); +// $ExpectType { kind: "a"; a: 3; } +exports.yun = unwrap(exports.y); +// $ExpectType { kind: "a"; a: 3; } +exports.yone = unwrap(sepsis({ low: 1, sign: { kind: 'a', a: 3 } })); diff --git a/tests/baselines/reference/returnTypeInferenceNotTooBroad.symbols b/tests/baselines/reference/returnTypeInferenceNotTooBroad.symbols new file mode 100644 index 00000000000..6a79c2f29e3 --- /dev/null +++ b/tests/baselines/reference/returnTypeInferenceNotTooBroad.symbols @@ -0,0 +1,67 @@ +=== tests/cases/compiler/returnTypeInferenceNotTooBroad.ts === +type Signs = { kind: 'a'; a: 3; } | { kind: 'b'; b: 2; } | { kind: 'c'; c: 1; }; +>Signs : Symbol(Signs, Decl(returnTypeInferenceNotTooBroad.ts, 0, 0)) +>kind : Symbol(kind, Decl(returnTypeInferenceNotTooBroad.ts, 0, 14)) +>a : Symbol(a, Decl(returnTypeInferenceNotTooBroad.ts, 0, 25)) +>kind : Symbol(kind, Decl(returnTypeInferenceNotTooBroad.ts, 0, 37)) +>b : Symbol(b, Decl(returnTypeInferenceNotTooBroad.ts, 0, 48)) +>kind : Symbol(kind, Decl(returnTypeInferenceNotTooBroad.ts, 0, 60)) +>c : Symbol(c, Decl(returnTypeInferenceNotTooBroad.ts, 0, 71)) + +interface Opts { +>Opts : Symbol(Opts, Decl(returnTypeInferenceNotTooBroad.ts, 0, 80)) +>T : Symbol(T, Decl(returnTypeInferenceNotTooBroad.ts, 1, 15)) + + low?: number; +>low : Symbol(Opts.low, Decl(returnTypeInferenceNotTooBroad.ts, 1, 19)) + + sign?: T +>sign : Symbol(Opts.sign, Decl(returnTypeInferenceNotTooBroad.ts, 2, 17)) +>T : Symbol(T, Decl(returnTypeInferenceNotTooBroad.ts, 1, 15)) +} +interface Wrapper { +>Wrapper : Symbol(Wrapper, Decl(returnTypeInferenceNotTooBroad.ts, 4, 1)) +>T : Symbol(T, Decl(returnTypeInferenceNotTooBroad.ts, 5, 18)) +} +declare function sepsis(opts: Opts): Wrapper; +>sepsis : Symbol(sepsis, Decl(returnTypeInferenceNotTooBroad.ts, 6, 1)) +>T : Symbol(T, Decl(returnTypeInferenceNotTooBroad.ts, 7, 24)) +>Signs : Symbol(Signs, Decl(returnTypeInferenceNotTooBroad.ts, 0, 0)) +>opts : Symbol(opts, Decl(returnTypeInferenceNotTooBroad.ts, 7, 41)) +>Opts : Symbol(Opts, Decl(returnTypeInferenceNotTooBroad.ts, 0, 80)) +>T : Symbol(T, Decl(returnTypeInferenceNotTooBroad.ts, 7, 24)) +>Wrapper : Symbol(Wrapper, Decl(returnTypeInferenceNotTooBroad.ts, 4, 1)) +>T : Symbol(T, Decl(returnTypeInferenceNotTooBroad.ts, 7, 24)) + +declare function unwrap(w: Wrapper): T; +>unwrap : Symbol(unwrap, Decl(returnTypeInferenceNotTooBroad.ts, 7, 68)) +>T : Symbol(T, Decl(returnTypeInferenceNotTooBroad.ts, 8, 24)) +>w : Symbol(w, Decl(returnTypeInferenceNotTooBroad.ts, 8, 27)) +>Wrapper : Symbol(Wrapper, Decl(returnTypeInferenceNotTooBroad.ts, 4, 1)) +>T : Symbol(T, Decl(returnTypeInferenceNotTooBroad.ts, 8, 24)) +>T : Symbol(T, Decl(returnTypeInferenceNotTooBroad.ts, 8, 24)) + +export const y = sepsis({ low: 1, sign: { kind: 'a', a: 3 }}); +>y : Symbol(y, Decl(returnTypeInferenceNotTooBroad.ts, 9, 12)) +>sepsis : Symbol(sepsis, Decl(returnTypeInferenceNotTooBroad.ts, 6, 1)) +>low : Symbol(low, Decl(returnTypeInferenceNotTooBroad.ts, 9, 25)) +>sign : Symbol(sign, Decl(returnTypeInferenceNotTooBroad.ts, 9, 33)) +>kind : Symbol(kind, Decl(returnTypeInferenceNotTooBroad.ts, 9, 41)) +>a : Symbol(a, Decl(returnTypeInferenceNotTooBroad.ts, 9, 52)) + +// $ExpectType { kind: "a"; a: 3; } +export const yun = unwrap(y); +>yun : Symbol(yun, Decl(returnTypeInferenceNotTooBroad.ts, 11, 12)) +>unwrap : Symbol(unwrap, Decl(returnTypeInferenceNotTooBroad.ts, 7, 68)) +>y : Symbol(y, Decl(returnTypeInferenceNotTooBroad.ts, 9, 12)) + +// $ExpectType { kind: "a"; a: 3; } +export const yone = unwrap(sepsis({ low: 1, sign: { kind: 'a', a: 3 }})); +>yone : Symbol(yone, Decl(returnTypeInferenceNotTooBroad.ts, 13, 12)) +>unwrap : Symbol(unwrap, Decl(returnTypeInferenceNotTooBroad.ts, 7, 68)) +>sepsis : Symbol(sepsis, Decl(returnTypeInferenceNotTooBroad.ts, 6, 1)) +>low : Symbol(low, Decl(returnTypeInferenceNotTooBroad.ts, 13, 35)) +>sign : Symbol(sign, Decl(returnTypeInferenceNotTooBroad.ts, 13, 43)) +>kind : Symbol(kind, Decl(returnTypeInferenceNotTooBroad.ts, 13, 51)) +>a : Symbol(a, Decl(returnTypeInferenceNotTooBroad.ts, 13, 62)) + diff --git a/tests/baselines/reference/returnTypeInferenceNotTooBroad.types b/tests/baselines/reference/returnTypeInferenceNotTooBroad.types new file mode 100644 index 00000000000..a95d7012d17 --- /dev/null +++ b/tests/baselines/reference/returnTypeInferenceNotTooBroad.types @@ -0,0 +1,65 @@ +=== tests/cases/compiler/returnTypeInferenceNotTooBroad.ts === +type Signs = { kind: 'a'; a: 3; } | { kind: 'b'; b: 2; } | { kind: 'c'; c: 1; }; +>Signs : Signs +>kind : "a" +>a : 3 +>kind : "b" +>b : 2 +>kind : "c" +>c : 1 + +interface Opts { + low?: number; +>low : number + + sign?: T +>sign : T +} +interface Wrapper { +} +declare function sepsis(opts: Opts): Wrapper; +>sepsis : (opts: Opts) => Wrapper +>opts : Opts + +declare function unwrap(w: Wrapper): T; +>unwrap : (w: Wrapper) => T +>w : Wrapper + +export const y = sepsis({ low: 1, sign: { kind: 'a', a: 3 }}); +>y : Wrapper<{ kind: "a"; a: 3; }> +>sepsis({ low: 1, sign: { kind: 'a', a: 3 }}) : Wrapper<{ kind: "a"; a: 3; }> +>sepsis : (opts: Opts) => Wrapper +>{ low: 1, sign: { kind: 'a', a: 3 }} : { low: number; sign: { kind: "a"; a: 3; }; } +>low : number +>1 : 1 +>sign : { kind: "a"; a: 3; } +>{ kind: 'a', a: 3 } : { kind: "a"; a: 3; } +>kind : "a" +>'a' : "a" +>a : 3 +>3 : 3 + +// $ExpectType { kind: "a"; a: 3; } +export const yun = unwrap(y); +>yun : { kind: "a"; a: 3; } +>unwrap(y) : { kind: "a"; a: 3; } +>unwrap : (w: Wrapper) => T +>y : Wrapper<{ kind: "a"; a: 3; }> + +// $ExpectType { kind: "a"; a: 3; } +export const yone = unwrap(sepsis({ low: 1, sign: { kind: 'a', a: 3 }})); +>yone : { kind: "a"; a: 3; } +>unwrap(sepsis({ low: 1, sign: { kind: 'a', a: 3 }})) : { kind: "a"; a: 3; } +>unwrap : (w: Wrapper) => T +>sepsis({ low: 1, sign: { kind: 'a', a: 3 }}) : Wrapper<{ kind: "a"; a: 3; }> +>sepsis : (opts: Opts) => Wrapper +>{ low: 1, sign: { kind: 'a', a: 3 }} : { low: number; sign: { kind: "a"; a: 3; }; } +>low : number +>1 : 1 +>sign : { kind: "a"; a: 3; } +>{ kind: 'a', a: 3 } : { kind: "a"; a: 3; } +>kind : "a" +>'a' : "a" +>a : 3 +>3 : 3 + diff --git a/tests/cases/compiler/returnTypeInferenceNotTooBroad.ts b/tests/cases/compiler/returnTypeInferenceNotTooBroad.ts new file mode 100644 index 00000000000..1573b3d72e0 --- /dev/null +++ b/tests/cases/compiler/returnTypeInferenceNotTooBroad.ts @@ -0,0 +1,14 @@ +type Signs = { kind: 'a'; a: 3; } | { kind: 'b'; b: 2; } | { kind: 'c'; c: 1; }; +interface Opts { + low?: number; + sign?: T +} +interface Wrapper { +} +declare function sepsis(opts: Opts): Wrapper; +declare function unwrap(w: Wrapper): T; +export const y = sepsis({ low: 1, sign: { kind: 'a', a: 3 }}); +// $ExpectType { kind: "a"; a: 3; } +export const yun = unwrap(y); +// $ExpectType { kind: "a"; a: 3; } +export const yone = unwrap(sepsis({ low: 1, sign: { kind: 'a', a: 3 }})); \ No newline at end of file From b1a73ab560ef0f0a681f7aa171b349d05a16e00b Mon Sep 17 00:00:00 2001 From: Wesley Wigham Date: Thu, 28 Feb 2019 13:52:57 -0800 Subject: [PATCH 134/149] Resolve aliases to jsx namespace symbol (#30160) --- src/compiler/checker.ts | 2 +- .../reference/jsxNamespaceReexports.js | 32 +++++++++++++++++++ .../reference/jsxNamespaceReexports.symbols | 31 ++++++++++++++++++ .../reference/jsxNamespaceReexports.types | 27 ++++++++++++++++ .../cases/compiler/jsxNamespaceReexports.tsx | 18 +++++++++++ 5 files changed, 109 insertions(+), 1 deletion(-) create mode 100644 tests/baselines/reference/jsxNamespaceReexports.js create mode 100644 tests/baselines/reference/jsxNamespaceReexports.symbols create mode 100644 tests/baselines/reference/jsxNamespaceReexports.types create mode 100644 tests/cases/compiler/jsxNamespaceReexports.tsx diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index eadf654e3a2..9b59cb3574d 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -18897,7 +18897,7 @@ namespace ts { const namespaceName = getJsxNamespace(location); const resolvedNamespace = resolveName(location, namespaceName, SymbolFlags.Namespace, /*diagnosticMessage*/ undefined, namespaceName, /*isUse*/ false); if (resolvedNamespace) { - const candidate = getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, SymbolFlags.Namespace); + const candidate = resolveSymbol(getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, SymbolFlags.Namespace)); if (candidate) { if (links) { links.jsxNamespace = candidate; diff --git a/tests/baselines/reference/jsxNamespaceReexports.js b/tests/baselines/reference/jsxNamespaceReexports.js new file mode 100644 index 00000000000..55c5ca4637e --- /dev/null +++ b/tests/baselines/reference/jsxNamespaceReexports.js @@ -0,0 +1,32 @@ +//// [tests/cases/compiler/jsxNamespaceReexports.tsx] //// + +//// [library.ts] +function createElement(element: string, props: any, ...children: any[]): any {} + +namespace JSX { + export interface IntrinsicElements { + [key: string]: Record; + } +} + +export { createElement, JSX }; +//// [index.tsx] +import * as MyLib from "./library"; + +const content = ; + +//// [library.js] +"use strict"; +exports.__esModule = true; +function createElement(element, props) { + var children = []; + for (var _i = 2; _i < arguments.length; _i++) { + children[_i - 2] = arguments[_i]; + } +} +exports.createElement = createElement; +//// [index.js] +"use strict"; +exports.__esModule = true; +var MyLib = require("./library"); +var content = MyLib.createElement("my-element", null); diff --git a/tests/baselines/reference/jsxNamespaceReexports.symbols b/tests/baselines/reference/jsxNamespaceReexports.symbols new file mode 100644 index 00000000000..c0a2c786d39 --- /dev/null +++ b/tests/baselines/reference/jsxNamespaceReexports.symbols @@ -0,0 +1,31 @@ +=== tests/cases/compiler/library.ts === +function createElement(element: string, props: any, ...children: any[]): any {} +>createElement : Symbol(createElement, Decl(library.ts, 0, 0)) +>element : Symbol(element, Decl(library.ts, 0, 23)) +>props : Symbol(props, Decl(library.ts, 0, 39)) +>children : Symbol(children, Decl(library.ts, 0, 51)) + +namespace JSX { +>JSX : Symbol(JSX, Decl(library.ts, 0, 79)) + + export interface IntrinsicElements { +>IntrinsicElements : Symbol(IntrinsicElements, Decl(library.ts, 2, 15)) + + [key: string]: Record; +>key : Symbol(key, Decl(library.ts, 4, 5)) +>Record : Symbol(Record, Decl(lib.es5.d.ts, --, --)) + } +} + +export { createElement, JSX }; +>createElement : Symbol(createElement, Decl(library.ts, 8, 8)) +>JSX : Symbol(JSX, Decl(library.ts, 8, 23)) + +=== tests/cases/compiler/index.tsx === +import * as MyLib from "./library"; +>MyLib : Symbol(MyLib, Decl(index.tsx, 0, 6)) + +const content = ; +>content : Symbol(content, Decl(index.tsx, 2, 5)) +>my-element : Symbol(MyLib.JSX.IntrinsicElements, Decl(library.ts, 2, 15)) + diff --git a/tests/baselines/reference/jsxNamespaceReexports.types b/tests/baselines/reference/jsxNamespaceReexports.types new file mode 100644 index 00000000000..857915efe39 --- /dev/null +++ b/tests/baselines/reference/jsxNamespaceReexports.types @@ -0,0 +1,27 @@ +=== tests/cases/compiler/library.ts === +function createElement(element: string, props: any, ...children: any[]): any {} +>createElement : (element: string, props: any, ...children: any[]) => any +>element : string +>props : any +>children : any[] + +namespace JSX { + export interface IntrinsicElements { + [key: string]: Record; +>key : string + } +} + +export { createElement, JSX }; +>createElement : (element: string, props: any, ...children: any[]) => any +>JSX : any + +=== tests/cases/compiler/index.tsx === +import * as MyLib from "./library"; +>MyLib : typeof MyLib + +const content = ; +>content : error +> : error +>my-element : any + diff --git a/tests/cases/compiler/jsxNamespaceReexports.tsx b/tests/cases/compiler/jsxNamespaceReexports.tsx new file mode 100644 index 00000000000..481fd7da2ca --- /dev/null +++ b/tests/cases/compiler/jsxNamespaceReexports.tsx @@ -0,0 +1,18 @@ + +// @jsx: react +// @jsxFactory: MyLib.createElement +// @strict: true +// @filename: library.ts +function createElement(element: string, props: any, ...children: any[]): any {} + +namespace JSX { + export interface IntrinsicElements { + [key: string]: Record; + } +} + +export { createElement, JSX }; +// @filename: index.tsx +import * as MyLib from "./library"; + +const content = ; \ No newline at end of file From 00bf32ca3967b07e8663d0cd2b3e2bbf572da88b Mon Sep 17 00:00:00 2001 From: Daniel Rosenwasser Date: Thu, 28 Feb 2019 14:35:03 -0800 Subject: [PATCH 135/149] Update LKG. --- lib/enu/diagnosticMessages.generated.json.lcg | 228 +- lib/lib.dom.d.ts | 872 ++- lib/lib.dom.iterable.d.ts | 7 + lib/lib.es2017.sharedmemory.d.ts | 4 +- lib/lib.es2018.asynciterable.d.ts | 44 + lib/lib.es2018.d.ts | 1 + lib/lib.es2019.array.d.ts | 223 + lib/lib.es2019.d.ts | 24 + lib/lib.es2019.full.d.ts | 25 + lib/lib.es2019.string.d.ts | 33 + lib/lib.es2019.symbol.d.ts | 26 + lib/lib.es5.d.ts | 102 +- lib/lib.esnext.d.ts | 5 +- lib/lib.webworker.d.ts | 184 +- lib/protocol.d.ts | 4 +- lib/tr/diagnosticMessages.generated.json | 2 +- lib/tsc.js | 4007 +++++++---- lib/tsserver.js | 5951 ++++++++++------ lib/tsserverlibrary.d.ts | 84 +- lib/tsserverlibrary.js | 6006 +++++++++++------ lib/typescript.d.ts | 59 +- lib/typescript.js | 5580 +++++++++------ lib/typescriptServices.d.ts | 59 +- lib/typescriptServices.js | 5579 +++++++++------ lib/typingsInstaller.js | 4518 ++++++++----- lib/zh-tw/diagnosticMessages.generated.json | 6 +- 26 files changed, 22528 insertions(+), 11105 deletions(-) create mode 100644 lib/lib.es2018.asynciterable.d.ts create mode 100644 lib/lib.es2019.array.d.ts create mode 100644 lib/lib.es2019.d.ts create mode 100644 lib/lib.es2019.full.d.ts create mode 100644 lib/lib.es2019.string.d.ts create mode 100644 lib/lib.es2019.symbol.d.ts diff --git a/lib/enu/diagnosticMessages.generated.json.lcg b/lib/enu/diagnosticMessages.generated.json.lcg index 61eb41991c4..17f927a74f3 100644 --- a/lib/enu/diagnosticMessages.generated.json.lcg +++ b/lib/enu/diagnosticMessages.generated.json.lcg @@ -27,6 +27,18 @@ + + + + + + + + + + + + @@ -129,6 +141,12 @@ + + + + + + @@ -849,12 +867,6 @@ - - - - - - @@ -1005,6 +1017,12 @@ + + + + + + @@ -1329,6 +1347,12 @@ + + + + + + @@ -1487,17 +1511,35 @@ - + - + + + + + + + + + + + + + - + + + + + + + @@ -1707,6 +1749,12 @@ + + + + + + @@ -2235,12 +2283,6 @@ - - - - - - @@ -2307,6 +2349,12 @@ + + + + + + @@ -2403,6 +2451,12 @@ + + + + + + @@ -2655,6 +2709,12 @@ + + + + + + @@ -3189,12 +3249,6 @@ - - - - - - @@ -3741,12 +3795,6 @@ - - - - - - @@ -3867,6 +3915,12 @@ + + + + + + @@ -4137,12 +4191,6 @@ - - - - - - @@ -4671,6 +4719,12 @@ + + + + + + @@ -4773,6 +4827,12 @@ + + + + + + @@ -5271,9 +5331,9 @@ - + - + @@ -5511,9 +5571,9 @@ - + - + @@ -5571,6 +5631,12 @@ + + + + + + @@ -5805,6 +5871,18 @@ + + + + + + + + + + + + @@ -5823,6 +5901,18 @@ + + + + + + + + + + + + @@ -5871,9 +5961,9 @@ - + - + @@ -5907,18 +5997,6 @@ - - - - - - - - - - - - @@ -5949,12 +6027,6 @@ - - - - - - @@ -6081,6 +6153,12 @@ + + + + + + @@ -6189,6 +6267,12 @@ + + + + + + @@ -6387,6 +6471,12 @@ + + + + + + @@ -6519,6 +6609,12 @@ + + + + + + @@ -6693,6 +6789,12 @@ + + + + + + @@ -6789,6 +6891,12 @@ + + + + + + @@ -6999,6 +7107,12 @@ + + + + + + diff --git a/lib/lib.dom.d.ts b/lib/lib.dom.d.ts index 464dea83926..7817a0e4267 100644 --- a/lib/lib.dom.d.ts +++ b/lib/lib.dom.d.ts @@ -203,6 +203,10 @@ interface ClientQueryOptions { type?: ClientTypes; } +interface ClipboardEventInit extends EventInit { + clipboardData?: DataTransfer | null; +} + interface CloseEventInit extends EventInit { code?: number; reason?: string; @@ -448,6 +452,10 @@ interface EventModifierInit extends UIEventInit { shiftKey?: boolean; } +interface EventSourceInit { + withCredentials?: boolean; +} + interface ExceptionInformation { domain?: string | null; } @@ -479,12 +487,16 @@ interface FocusOptions { preventScroll?: boolean; } +interface FullscreenOptions { + navigationUI?: FullscreenNavigationUI; +} + interface GainOptions extends AudioNodeOptions { gain?: number; } interface GamepadEventInit extends EventInit { - gamepad?: Gamepad; + gamepad: Gamepad; } interface GetNotificationOptions { @@ -619,15 +631,17 @@ interface MediaEncryptedEventInit extends EventInit { } interface MediaKeyMessageEventInit extends EventInit { - message?: ArrayBuffer | null; - messageType?: MediaKeyMessageType; + message: ArrayBuffer; + messageType: MediaKeyMessageType; } interface MediaKeySystemConfiguration { audioCapabilities?: MediaKeySystemMediaCapability[]; distinctiveIdentifier?: MediaKeysRequirement; initDataTypes?: string[]; + label?: string; persistentState?: MediaKeysRequirement; + sessionTypes?: string[]; videoCapabilities?: MediaKeySystemMediaCapability[]; } @@ -744,6 +758,8 @@ interface MouseEventInit extends EventModifierInit { buttons?: number; clientX?: number; clientY?: number; + movementX?: number; + movementY?: number; relatedTarget?: EventTarget | null; screenX?: number; screenY?: number; @@ -1462,6 +1478,11 @@ interface ServiceWorkerMessageEventInit extends EventInit { source?: ServiceWorker | MessagePort | null; } +interface ShadowRootInit { + delegatesFocus?: boolean; + mode: ShadowRootMode; +} + interface StereoPannerOptions extends AudioNodeOptions { pan?: number; } @@ -1629,6 +1650,7 @@ interface EventListener { (evt: Event): void; } +/** The ANGLE_instanced_arrays extension is part of the WebGL API and allows to draw the same object, or groups of similar objects multiple times, if they share the same vertex data, primitive count and type. */ interface ANGLE_instanced_arrays { drawArraysInstancedANGLE(mode: GLenum, first: GLint, count: GLsizei, primcount: GLsizei): void; drawElementsInstancedANGLE(mode: GLenum, count: GLsizei, type: GLenum, offset: GLintptr, primcount: GLsizei): void; @@ -1636,6 +1658,7 @@ interface ANGLE_instanced_arrays { readonly VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE: GLenum; } +/** The AbortController interface represents a controller object that allows you to abort one or more DOM requests as and when desired. */ interface AbortController { /** * Returns the AbortSignal object associated with this object. @@ -1654,16 +1677,17 @@ declare var AbortController: { }; interface AbortSignalEventMap { - "abort": ProgressEvent; + "abort": Event; } +/** The AbortSignal interface represents a signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object. */ interface AbortSignal extends EventTarget { /** * Returns true if this AbortSignal's AbortController has signaled to abort, and false * otherwise. */ readonly aborted: boolean; - onabort: ((this: AbortSignal, ev: ProgressEvent) => any) | null; + onabort: ((this: AbortSignal, ev: Event) => any) | null; addEventListener(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -1708,6 +1732,7 @@ interface AesCmacParams extends Algorithm { length: number; } +/** The AnalyserNode interface represents a node able to provide real-time frequency and time-domain analysis information. It is an AudioNode that passes the audio stream unchanged from the input to the output, but allows you to take the generated data, process it, and create audio visualizations. */ interface AnalyserNode extends AudioNode { fftSize: number; readonly frequencyBinCount: number; @@ -1776,6 +1801,7 @@ declare var AnimationEffect: { new(): AnimationEffect; }; +/** The AnimationEvent interface represents events providing information related to animations. */ interface AnimationEvent extends Event { readonly animationName: string; readonly elapsedTime: number; @@ -1865,6 +1891,7 @@ declare var ApplicationCache: { readonly UPDATEREADY: number; }; +/** This type represents a DOM element's attribute as an object. In most DOM methods, you will probably directly retrieve the attribute as a string (e.g., Element.getAttribute(), but certain functions (e.g., Element.getAttributeNode()) or means of iterating give Attr types. */ interface Attr extends Node { readonly localName: string; readonly name: string; @@ -1880,6 +1907,7 @@ declare var Attr: { new(): Attr; }; +/** Objects of these types are designed to hold small audio snippets, typically less than 45 s. For longer sounds, objects implementing the MediaElementAudioSourceNode are more suitable. The buffer contains data in the following format:  non-interleaved IEEE754 32-bit linear PCM with a nominal range between -1 and +1, that is, 32bits floating point buffer, with each samples between -1.0 and 1.0. If the AudioBuffer has multiple channels, they are stored in separate buffer. */ interface AudioBuffer { readonly duration: number; readonly length: number; @@ -1895,6 +1923,7 @@ declare var AudioBuffer: { new(options: AudioBufferOptions): AudioBuffer; }; +/** The AudioBufferSourceNode interface is an AudioScheduledSourceNode which represents an audio source consisting of in-memory audio data, stored in an AudioBuffer. It's especially useful for playing back audio which has particularly stringent timing accuracy requirements, such as for sounds that must match a specific rhythm and can be kept in memory rather than being played from disk or the network. */ interface AudioBufferSourceNode extends AudioScheduledSourceNode { buffer: AudioBuffer | null; readonly detune: AudioParam; @@ -1914,6 +1943,7 @@ declare var AudioBufferSourceNode: { new(context: BaseAudioContext, options?: AudioBufferSourceOptions): AudioBufferSourceNode; }; +/** The AudioContext interface represents an audio-processing graph built from audio modules linked together, each represented by an AudioNode. */ interface AudioContext extends BaseAudioContext { readonly baseLatency: number; readonly outputLatency: number; @@ -1935,6 +1965,7 @@ declare var AudioContext: { new(contextOptions?: AudioContextOptions): AudioContext; }; +/** AudioDestinationNode has no output (as it is the output, no more AudioNode can be linked after it in the audio graph) and one input. The number of channels in the input must be between 0 and the maxChannelCount value or an exception is raised. */ interface AudioDestinationNode extends AudioNode { readonly maxChannelCount: number; } @@ -1944,6 +1975,7 @@ declare var AudioDestinationNode: { new(): AudioDestinationNode; }; +/** The AudioListener interface represents the position and orientation of the unique person listening to the audio scene, and is used in audio spatialization. All PannerNodes spatialize in relation to the AudioListener stored in the BaseAudioContext.listener attribute. */ interface AudioListener { readonly forwardX: AudioParam; readonly forwardY: AudioParam; @@ -1965,6 +1997,7 @@ declare var AudioListener: { new(): AudioListener; }; +/** The AudioNode interface is a generic interface for representing an audio processing module. Examples include: */ interface AudioNode extends EventTarget { channelCount: number; channelCountMode: ChannelCountMode; @@ -1988,6 +2021,7 @@ declare var AudioNode: { new(): AudioNode; }; +/** The Web Audio API's AudioParam interface represents an audio-related parameter, usually a parameter of an AudioNode (such as GainNode.gain). */ interface AudioParam { automationRate: AutomationRate; readonly defaultValue: number; @@ -2017,6 +2051,7 @@ declare var AudioParamMap: { new(): AudioParamMap; }; +/** The Web Audio API AudioProcessingEvent represents events that occur when a ScriptProcessorNode input buffer is ready to be processed. */ interface AudioProcessingEvent extends Event { readonly inputBuffer: AudioBuffer; readonly outputBuffer: AudioBuffer; @@ -2047,13 +2082,14 @@ declare var AudioScheduledSourceNode: { new(): AudioScheduledSourceNode; }; +/** The AudioTrack interface represents a single audio track from one of the HTML media elements,