TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Allow a module to implement an interface

Open ivogabe opened this issue 10 years ago • 63 comments

It would be useful when a module can implement an interface using the implements keyword. Syntax: module MyModule implements MyInterface { ... }.

Example:

interface Showable {
    show(): void;
}
function addShowable(showable: Showable) {

}

// This works:
module Login {
    export function show() {
        document.getElementById('login').style.display = 'block';
    }
}
addShowable(Login);

// This doesn't work (yet?)
module Menu implements Showable {
    export function show() {
        document.getElementById('menu').style.display = 'block';
    }
}
addShowable(Menu);

ivogabe avatar Aug 10 '14 10:08 ivogabe

How would this work with external modules? It's likely once people can use it for internal, they'll also want to use it with external.

sophiajt avatar Aug 15 '14 18:08 sophiajt

That's a good question. I don't know which syntax would be the best, but here are a few suggestions:

implements Showable; // I would prefer this one.
module implements Showable;
export implements Showable;

It should only be allowed on external modules that don't use an export assignment, since if you use an export assignment, the thing that you export can already have an implements on another place.

ivogabe avatar Aug 15 '14 19:08 ivogabe

Approved. We prefer the syntax

export implements Showable;

and agreed that this is unneeded for files export = assignments.

RyanCavanaugh avatar Aug 15 '14 19:08 RyanCavanaugh

Some more questions:

  • Since we are allowing modules to have types at declaration sites, should not we allow them to have types at use sites as well. e.g.:
declare module "Module" implements Interface { }

import i : Interface = require("Module");
  • What do you do with merged declarations, should you enforce the interface on the aggregate of all declarations? and what happens if they do not match in visibility? e.g.:
module Foo {
    export interface IBar {
        (a:string): void;
    }

    export module Bar implements IBar {  // should this be an error?
        export interface Interface {}
    }    

    function Bar(a: string) : void { }  // not exported
}

var bar: Foo.IBar = Foo.Bar;

mhegazy avatar Aug 15 '14 19:08 mhegazy

It should be allowed on ambient external modules. For these modules two syntaxes should be allowed in my opinion:

declare module "first" implements Foo { }
declare module "second"  {
  interface Bar { }
  export implements Bar; // this syntax is necessary, with the first syntax you can't reference Bar.  
}

Or should Bar be in the scope in an implements clause before the opening {?

Adding type info to an import statement isn't really useful in my opinion, since you can add the type info to the module itself.

And for merged declarations, I'd say that the module block that contains the implements clause should implement the interface. That also prevents issues with visibility.

ivogabe avatar Aug 15 '14 20:08 ivogabe

How would this be related to #2159? A namespace implements an interface?

jbondc avatar Apr 14 '15 12:04 jbondc

@jbondc If we had this, it would also apply to namespaces. You should think of internal modules and namespaces as isomorphic.

DanielRosenwasser avatar Apr 14 '15 17:04 DanielRosenwasser

Are you sure you want to go down an implementational path where "namespaces" can implement interfaces?

Elephant-Vessel avatar Jan 04 '16 15:01 Elephant-Vessel

Oh wow, this has been approved for quite a while. @RyanCavanaugh, @DanielRosenwasser, @mhegazy unless you have any second thoughts or tweaks, I'll probably implement this soonish.

joelday avatar Jan 02 '17 18:01 joelday

I withdraw my previous skepticism, I actually exited for the new structural possibilities it would bring.

In line with that, please consider enforcing the interface of the aggregate of the interface instead of only the block that declares the implementation - The nature of namespaces/modules is to be spread out and to contain a lot of non-trivial components. I'd like to be able to use this, but I certainly don't want to define my whole namespace/module in the same file. Why not just use a class in that case?

Elephant-Vessel avatar Jan 08 '17 00:01 Elephant-Vessel

@Elephant-Vessel I'm not sure if we are talking about Modules, or Namespaces, or Packages, or Features, or...

aluanhaddad avatar Jan 08 '17 04:01 aluanhaddad

@aluanhaddad What do you mean?

Elephant-Vessel avatar Jan 08 '17 09:01 Elephant-Vessel

I mean that at the time that this discussion started module didn't mean what it means today. We now use the term namespace to refer to what is described in the OP as a module, while module has taken on a more precise and incompatible meaning. So when you talk about multiple files taking part in this implementation are you referring to namespaces or modules?

aluanhaddad avatar Jan 08 '17 09:01 aluanhaddad

I'm referring to namespaces. I guess I just wanted to conform to the history of this thread, sorry for not breaking loose :) Or when I think of it, maybe I had the generic term 'module' in my head, describing a higher-level unit consisting of set of sub-components, assembled to provide certain high-level functionality in a system. But I'm fine with just going with 'namespaces'.

Elephant-Vessel avatar Jan 08 '17 10:01 Elephant-Vessel

So I want to be able to describe and put constraints and expectations on [generic modules] that can contain other [generic modules] or classes, taking advantage of the structural concept namespaces in typescript.

My hope is that we'll be able to better express higher-level structural expectations in a system. Classes do not scale well, they are fine as atomic components in a system, but I don't think that higher-level organizational structure in a system would good to express with classes as they are designed to be instantiated and inherited and stuff like that. It's just too bloaty.

I'd appreciate a simple and clean way to describe higher order structure of the system, no fuss. Preferably with the only fuss being optional directional visibility constraints. Like making it impossible to reference MySystem.ClientApplication from MySystem.Infrastructure but fine the other way around. Then we'd start to go somewhere exciting.

Elephant-Vessel avatar Jan 08 '17 10:01 Elephant-Vessel

@Elephant-Vessel thanks for clarifying. I agree this would be extremely valuable and that class types are not the right approach here. I think you hit the nail on the head when talking about instantiation because namespaces represent things that are conceptually singletons at the library level. Although this can't be enforced, it would be useful conceptually to have something that does not imply multiple instantiations.

aluanhaddad avatar Jan 09 '17 03:01 aluanhaddad

I agree with @Elephant-Vessel. While it is easy to mistaken TypeScript for another Java, where all constraints are expressed with a single class structure, TS has a much broader "Shape" concept which is very powerful and eliminates semantic contortonism. Unfortunately, the inability to put constraints on module tend to force developers to relegate back to a class pattern for things that would be much better expressed as module.

For example, for unit testing, it would be very helpful to be able to express some "shape" (i.e. constraints) on modules so that we can provide alternative implementation for a particular running context. Now, it seems the only way to do that in a structure/checked way is to go back to class based DI (as la Spring) and make everything a class (and therefore instantiable).

Anyway, I am paraphrasing @Elephant-Vessel, but if I have a single wish for TS, it would be this one.

jeremychone avatar Oct 20 '17 00:10 jeremychone

Any word on this bird? I have this issue as well

soooo, uhh, wouldn't it be a simple case of:

export {} as IFooBar;

what's wrong with that syntax? I guess the syntax has already been approved, perhaps as

export implements IFooBar

anyway looking forward to it

ORESoftware avatar Oct 28 '17 21:10 ORESoftware

Has this matriculated / landed yet? this is going to be a cool feature

ORESoftware avatar May 07 '18 20:05 ORESoftware

How can we progress this? Its incredibly powerful. Happy to help out!

chrisui avatar Jul 26 '18 09:07 chrisui

any worb on this birb? One question I have for the moment, is how can I declare an interface for the default export. For example:

export default {}

I suppose I can just do:

const x: MyInterface = {}
export default x;

that would work for most TS files, the problem with it tho, is that if you are coding for JS first and planning to transition to TS later, then this doesn't work so well.

Another thing I was thinking of, what about namespaces that implement? Something like:

export namespace Foo implements Bar {

}

I guess Bar would be an abstract namespace lol idk

ORESoftware avatar Nov 01 '18 18:11 ORESoftware

Seen this question rise up so many times, and I think we are all just looking for one thing: Support static members in an interface. If that would happen, you could just use a class with static members and an interface, which is almost the same thing as you are trying to do here, right?

Either way, add static support to interfaces OR add interface support for modules is highly needed.

shaipetel avatar Nov 23 '18 19:11 shaipetel

@shiapetel nah not like that.

we can do this:

export default <T>{
  foo: Foo,
  bar: Bar
}

but that's not what we are looking for. we are specifically looking for:

export const foo : Foo = {};
export const bar : Bar = {};

but there's currently no mechanism to enforce the module to export foo and bar. And in fact there's no mechanism to enforce that the module export the right default value either.

ORESoftware avatar Nov 24 '18 09:11 ORESoftware

If interfaces supported static members, you could use a class with static foo/bar that inherited from: Interface ILoveFooBar{ static foo:FooType; static bar:BarType; }

Right? That’s what I meant, I think it would help in your situation- I know it would definitely help in mine.

shaipetel avatar Nov 24 '18 17:11 shaipetel

@shaipetel static members of interfaces definitely might be useful, but perhaps not for this use case.

ORESoftware avatar Nov 24 '18 20:11 ORESoftware

Is this issue just waiting for someone to have a go at implementing?

danielbodart avatar Jul 10 '19 08:07 danielbodart

One use case would be for frameworks and tools that scan a directory for modules on application startup, expecting those modules all to export a certain shape.

For example, Next.js scans ./pages/**/*.{ts,tsx} for your page modules, generating routes based on your filenames. It's up to you to ensure each module exports the right things (a NextPage as the default export, and an optional PageConfig export named config):

import { NextPage, PageConfig } from 'next'

interface Props { userAgent?: string }

const Home: NextPage<Props> = ({ userAgent }) => (<main>...</main>)

Page.getInitialProps = async ({ req }) => {
  const userAgent = req ? req.headers['user-agent'] : navigator.userAgent
  return { userAgent }
}

export default Page

export const config: PageConfig = {
  api: { bodyParser: false }
}

It would be nice if you could instead declare the export shape of the whole module in one line near the top, like implements NextPageModule<Props>.

Another thought: it would be interesting if there was some way to specify in a TypeScript config that all files matching a certain pattern (like ./pages/**/*.{ts,tsx}) must implement a certain export shape, so a module could have its exports type-checked purely because it's located within the pages directory for example. But I'm not sure if there's any precedent for this approach, and it might get confusing.

callumlocke avatar Oct 08 '19 13:10 callumlocke

I find I'm often tempted to create a Singleton Class when a simple module that implements an interface is all I need. Any tips how best to address this?

kdubious avatar Nov 27 '19 17:11 kdubious

Thinking about this from a 2020 perspective, I wonder if instead of export implements Showable we re-use type and allow export as an identifier? Today that's invalid syntax so it's unlikely to step on anyone's existing codebase.

Then we get the import syntax:

// Can re-use the import syntax
type export = import("webpack").Config

Declarations are then easy to write:

// Can use normal literals
type export = { test: () => string, description: string }

// Generics are easy
type export = (props: any) => React.SFC<MyCustomModule>

It's also worth thinking what the JSDoc equivalent should be too, maybe:

/** @typedef {import ("webpack").Config} export */

orta avatar May 17 '20 20:05 orta

There's some notes in ^ - one interesting thing that came out of the meeting was the idea that could we build a more generic tool of which this is a use-case, rather than the only thing it does.

For example, if we had a type assertion operator for type compatibility then that could be used for both the module exports, and generically to verify that types match how you want. For example:

type assert is import("webpack").Config

const path = require('path');

export default {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  }
};

Where the lack of a target means applying it at the top level scope. This can be used to provide contextual typing (e.g. you'd get auto-complete in the export default { en|

But can also be useful in validating your own types:

import {someFunction} from "./example"

type assert ReturnType<typeof someFunction> is string

orta avatar May 21 '20 20:05 orta