TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

define properties with getters and setters on namespaces

Open bendmorris opened this issue 3 years ago • 0 comments

Suggestion

I'm hoping to revisit https://github.com/microsoft/TypeScript/issues/16478 but narrowed to only namespaces, not modules. I agree with the reasoning for not considering this features for ES modules, but I think the feature still makes a lot of sense for namespaces.

I work at Netflix (so we are basically coworkers :smile:) and my TS code runs on TVs and other devices in a custom JS environment. I want to use a namespace to describe platform-provided, globally scoped, custom objects. These objects can include properties with getters and setters (which are typed differently) and currently there's no syntax available to describe that.

I can think of two ways to implement this:

  • export get x(): T; as suggested in the linked proposal. Pro: it feels like a very natural syntax. Con: namespaces would support a feature that modules do not.
  • Namespace declarations define an implicit interface, similar to classes, which can be added to in a subsequent interface declaration:
declare namespace MyNamespace {}

interface MyNamespace {
    get myValue(): number;
}

Pro: no new syntax. Con: potential name collision - currently you can have an interface with the same name as a namespace, and the interface will win. With this change the two would be merged.

This feature would be really valuable to me, so I wanted to see if this idea is objectionable to the core team or not - if it's acceptable but niche or wouldn't be a priority, I'm willing to get my hands dirty and submit a PR.

✅ Viability Checklist

My suggestion meets these guidelines:

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

bendmorris avatar Sep 22 '22 23:09 bendmorris