Skip to content

Interface and TypeAlias should be forbidden in Statement position, currently causing invalid emit or crash #22686

@ajafff

Description

@ajafff

TypeScript Version: 2.8.0-dev.20180318

Search Terms:

TypeAlias

Code

if (Boolean())
    type T = number;
else
    type U = string;

Expected behavior:

Error: type alias declaration is not allowed in this position.

Actual behavior:

TypeError: Cannot read property 'kind' of undefined
    at Object.isBlock (/Users/klaus/code/wotan/node_modules/typescript/lib/tsc.js:9482:21)
    at emitEmbeddedStatement (/Users/klaus/code/wotan/node_modules/typescript/lib/tsc.js:58158:20)
    at emitIfStatement (/Users/klaus/code/wotan/node_modules/typescript/lib/tsc.js:57400:13)
    at pipelineEmitUnspecified (/Users/klaus/code/wotan/node_modules/typescript/lib/tsc.js:56654:28)
    at pipelineEmitWithHint (/Users/klaus/code/wotan/node_modules/typescript/lib/tsc.js:56525:32)
    at emitNodeWithSourceMap (/Users/klaus/code/wotan/node_modules/typescript/lib/tsc.js:54061:21)
    at pipelineEmitWithSourceMap (/Users/klaus/code/wotan/node_modules/typescript/lib/tsc.js:56513:17)
    at emitNodeWithComments (/Users/klaus/code/wotan/node_modules/typescript/lib/tsc.js:54192:17)
    at pipelineEmitWithComments (/Users/klaus/code/wotan/node_modules/typescript/lib/tsc.js:56505:17)
    at emitNodeWithNotification (/Users/klaus/code/wotan/node_modules/typescript/lib/tsc.js:53768:21)

Playground Link: http://www.typescriptlang.org/play/#src=if%20(Boolean())%0A%20%20%20%20type%20T%20%3D%20number%3B%0Aelse%0A%20%20%20%20type%20U%20%3D%20string%3B%0A

Interface

Code

if (Boolean())
    interface I {
        a: number
    }
else
    interface I {
        b: string;
    }

Expected behavior:

Error: interface declaration is not allowed in this position.

Actual behavior:

Invalid emit:

if (Boolean())
else

Playground Link: http://www.typescriptlang.org/play/#src=if%20(Boolean())%0A%20%20%20%20interface%20I%20%7B%0A%20%20%20%20%20%20%20%20a%3A%20number%0A%20%20%20%20%7D%0Aelse%0A%20%20%20%20interface%20I%20%7B%0A%20%20%20%20%20%20%20%20b%3A%20string%3B%0A%20%20%20%20%7D%0A

Related Issues:
#22682

IMO TypeAliasDeclaration and InterfaceDeclaration should be forbidden in that position to align with ClassDeclaration (once #22682 is fixed).
Otherwise the types are visible outside of the containing statement. That's pretty unintuitive, because users might think they can conditionally declare interfaces (see my interface code snippet), but in fact they are merged.

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScript

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions