fix(compiler): quote non identifiers in map keys. (#18788)

PR Close #18788
This commit is contained in:
Tobias Bosch 2017-08-18 15:02:10 -07:00 committed by Miško Hevery
parent c1a4621c8f
commit 2fbc92fd2e
2 changed files with 7 additions and 3 deletions

View File

@ -14,6 +14,7 @@ export interface Node { sourceSpan: ParseSourceSpan|null; }
const METHOD_THIS_NAME = 'this';
const CATCH_ERROR_NAME = 'error';
const CATCH_STACK_NAME = 'stack';
const _VALID_IDENTIFIER_RE = /^[$A-Z_][0-9A-Z_$]*$/i;
export class TypeScriptNodeEmitter {
updateSourceFile(sourceFile: ts.SourceFile, stmts: Statement[], preamble?: string):
@ -421,7 +422,9 @@ class _NodeEmitterVisitor implements StatementVisitor, ExpressionVisitor {
return this.record(
expr, ts.createObjectLiteral(expr.entries.map(
entry => ts.createPropertyAssignment(
entry.quoted ? ts.createLiteral(entry.key) : entry.key,
entry.quoted || !_VALID_IDENTIFIER_RE.test(entry.key) ?
ts.createLiteral(entry.key) :
entry.key,
entry.value.visitExpression(this, null)))));
}

View File

@ -169,10 +169,11 @@ describe('TypeScriptNodeEmitter', () => {
expect(emitStmt(o.literalMap([
{key: 'someKey', value: o.literal(1), quoted: false},
{key: 'a', value: o.literal('a'), quoted: false},
{key: '*', value: o.literal('star'), quoted: true},
{key: 'b', value: o.literal('b'), quoted: true},
{key: '*', value: o.literal('star'), quoted: false},
]).toStmt())
.replace(/\s+/gm, ''))
.toEqual(`({someKey:1,a:"a","*":"star"});`);
.toEqual(`({someKey:1,a:"a","b":"b","*":"star"});`);
});
it('should support blank literals', () => {