2

Is it possible to implement the following interface:

export interface Foo {
    (): void;

    bar: number;
}

Using classes?

This is the closest thing I could figure out:

var foo = function () { } as Foo;

foo.bar = 5;
4
  • 2
    The best way of determining if something is possible is to try it. Commented Nov 2, 2016 at 14:19
  • if you think about it.. that's what a class gets compiled to ;) Also. the handbook is a very good place to search for questions such as these. Commented Nov 2, 2016 at 14:30
  • In my answer I assumed that what you really want is some object that implements that interface, not necessarily a class. Is that correct? Commented Nov 2, 2016 at 15:14
  • I am trying to find the cleanest solution. Commented Nov 3, 2016 at 9:27

3 Answers 3

1

Although I'm not completely sure, I think this is not possible using classes without some serious hacks. I think this interface syntax is actually for supporting external library typings, where in many cases such constructions exist.

What you actually refer to in your sample code, is static members of a class. I mean a class with a public constructor and some static members is exactly this construction. But static members cannot be declared in interfaces (obviously).

Sign up to request clarification or add additional context in comments.

Comments

1

You can not have a class do this, but you can use type aliases and intersection types to do something like this:

// Define the type of your objects
type Foo = { (): void } & { bar: number };

// You could have a factory method to create instances
var fooFactoryMethod = (func: () => void, bar: number) => {
  var foo = func as Foo;
  foo.bar = bar;
  return foo;
}   

var myObject = fooFactoryMethod(() => { console.log("Hello world") }, 23)

// Or just creating them manually
var myObject2 = (() => { console.log("Hello world") }) as Foo;
myObject2.bar = 45;

// Now you can use it like this
var func = (arg: Foo) => {
  arg();
  arg.bar = 34;
}
func(myObject)

Playground

4 Comments

Modules behave differently than classes though.
@user3233089 Sure, but do you need classes here? What is your use-case?
I need to use class specific attributes: creating multiple instances of for example.
@user3233089 Did this help?
0

All classes are functions when they get compiled into js.

export class FooClass implements Foo {
    bar: number;

    constructor() {
        this.bar = 1;
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.