Skip to content

Shorter dot syntax to access enum values #45956

@FilipeBeck

Description

@FilipeBeck

Suggestion

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

Allow access to enum values without having to type the entire path to the value. Any subpath starting with dot is valid.

namespace Geometry {
  export enum Shape {
    CIRCLE,
    SQUARE
  }
}

function setShape(shape: Geometry.Shape) {
  // ...
}

setShape(.CIRCLE)
// too
setShape(.Shape.SQUARE)

With unions, we have a compiler error when the subpath is ambiguous.

namespace GeometryA {
  export enum ShapeA {
    CIRCLE = 1,
    SQUARE = 2,
  }
}

namespace GeometryB {
  export enum ShapeB {
    CIRCLE = 'circle',
    SQUARE = 'square',
  }
}

function setShape(shape: GeometryA.ShapeA | GeometryB.ShapeB) {
  // ...
}

setShape(.CIRCLE) // Error. Is `1` or `'circle'`?
setShape(.ShapeA.CIRCLE) // OK

📃 Motivating Example

Sometimes, the path is too long. I have this code in react:

<Scene sampleRate={88200} latencyHint={ATOM.Scene.LatencyCategory.PLAYBACK}>

Besides having to import ATOM, the path is too long. That way it would be better:

<Scene sampleRate={88200} latencyHint={.PLAYBACK}>

This example would emit an import of ATOM at runtime.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Out of ScopeThis idea sits outside of the TypeScript language design constraintsSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions