Use widened type (just like importing using module.exports = in js file)

Fixes #26429
This commit is contained in:
Sheetal Nandi 2018-08-14 13:24:39 -07:00
parent 50ccd91263
commit 9eb0c9a88f
3 changed files with 20 additions and 8 deletions

View File

@ -5092,7 +5092,14 @@ namespace ts {
// Handle export default expressions
if (isSourceFile(declaration)) {
const jsonSourceFile = cast(declaration, isJsonSourceFile);
return jsonSourceFile.statements.length ? checkExpression(jsonSourceFile.statements[0].expression) : emptyObjectType;
if (!jsonSourceFile.statements.length) {
return emptyObjectType;
}
const type = getWidenedLiteralType(checkExpression(jsonSourceFile.statements[0].expression));
if (type.flags & TypeFlags.Object) {
return getRegularTypeOfObjectLiteral(type);
}
return type;
}
if (declaration.kind === SyntaxKind.ExportAssignment) {
return checkExpression((<ExportAssignment>declaration).expression);

View File

@ -1,10 +1,12 @@
/user.js(2,7): error TS2339: Property 'b' does not exist on type '{ "a": number; }'.
/user.js(5,7): error TS2322: Type '{ "a": number; }' is not assignable to type '{ b: number; }'.
Property 'b' is missing in type '{ "a": number; }'.
/user.js(9,7): error TS2339: Property 'b' does not exist on type '{ "a": number; }'.
/user.js(12,7): error TS2322: Type '{ a: number; }' is not assignable to type '{ b: number; }'.
Property 'b' is missing in type '{ a: number; }'.
==== /user.js (3 errors) ====
==== /user.js (4 errors) ====
const json0 = require("./json.json");
json0.b; // Error (good)
~
@ -12,6 +14,9 @@
/** @type {{ b: number }} */
const json1 = require("./json.json"); // No error (bad)
~~~~~
!!! error TS2322: Type '{ "a": number; }' is not assignable to type '{ b: number; }'.
!!! error TS2322: Property 'b' is missing in type '{ "a": number; }'.
json1.b; // No error (OK since that's the type annotation)
const js0 = require("./js.js");

View File

@ -6,10 +6,10 @@ import c = require('./c.json');
>c : (string | null)[]
import d = require('./d.json');
>d : "dConfig"
>d : string
import e = require('./e.json');
>e : -10
>e : number
import f = require('./f.json');
>f : number[]
@ -64,14 +64,14 @@ const stringOrNumberOrNull: string | number | null = c[0];
>0 : 0
stringLiteral = d;
>stringLiteral = d : "dConfig"
>stringLiteral = d : string
>stringLiteral : string
>d : "dConfig"
>d : string
numberLiteral = e;
>numberLiteral = e : -10
>numberLiteral = e : number
>numberLiteral : number
>e : -10
>e : number
numberLiteral = f[0];
>numberLiteral = f[0] : number