Typescript: Should a `new` expression with type arguments need parentheses?

Created on 23 Mar 2020  路  4Comments  路  Source: microsoft/TypeScript

// @target es6

// @filename: file1.ts
let stuff1 = new Array<string>;

// @filename: file2.ts
let stuff2 = new Map<string, number>;

This code currently errors with

'(' expected.

I actually don't care if this code should be allowed or not.

Maybe it should, in which case this is a bug on needing to allow the code.

Maybe it shouldn't, in which case I think we should give a better error message like

A 'new' expression with type arguments must always be followed by a parenthesized argument list.
Error Messages Experience Enhancement Fixed Suggestion good first issue help wanted

Most helpful comment

Approximately infinity years ago we decided that parens were required in this case, to simplify the grammar and reduce the chances of ambiguity.

All 4 comments

Approximately infinity years ago we decided that parens were required in this case, to simplify the grammar and reduce the chances of ambiguity.

@DanielRosenwasser I want to working on it, can I take this? Could you please add more info about how to fix it?

  1. Add the new error message to src/compiler/diagnosticMessages.json
  2. Run npx gulp generate-diagnostics
  3. In src/compiler/parser.ts

    https://github.com/microsoft/TypeScript/blob/37569d01f6a67ef4cca4fac46dfbff646137b9d9/src/compiler/parser.ts#L5202

    you'll want to write something like

    if (token() === SyntaxKind.OpenParenToken) {
       node.arguments = parseArgumentList();
    }
    else if (node.typeArguments) {
       // issue the error here using parseErrorAt(fullStart, scanner.getStartPos(), ...)
    }
    
  4. Try running npx gulp runtests-parallel. There is at least one test that should break:

    https://github.com/microsoft/TypeScript/blob/37569d01f6a67ef4cca4fac46dfbff646137b9d9/tests/cases/conformance/expressions/newOperator/newOperatorErrorCases.ts#L32

  5. Run npx gulp baseline-accept

Thanks @Rustin-Liu!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

CyrusNajmabadi picture CyrusNajmabadi  路  3Comments

MartynasZilinskas picture MartynasZilinskas  路  3Comments

blendsdk picture blendsdk  路  3Comments

dlaberge picture dlaberge  路  3Comments

DanielRosenwasser picture DanielRosenwasser  路  3Comments