LosManos
LosManos

Reputation: 7692

How do I specify a callback in an interface in typescript but not have to name a type for it

I want to have an interface with a function delegate but not declare a type for it.

This works but there is a type CallbackType that I'd like to avoid.

export type CallbackType =
  (length: number) => void;

export interface MyInterface {
    myCallback:  CallbackType; // This works alright.
}

But what I would prefer is to not crowd the namespace with yet a type.

export interface MyInterface {
    myCallback: (length: number): void; // Does not work
}

(I could be persuaded that having a named type is a good idea and drop my mission to find another way. But that is not the Question.)

Upvotes: 0

Views: 33

Answers (2)

Robbie Milejczak
Robbie Milejczak

Reputation: 5780

You can use a different syntax for methods:

export interface MyInterface {
    myCallback(length: number): void;
}

This is essentially a shorthand for myCallback: (length: number) => void;

Upvotes: 1

Gonzalo Muro
Gonzalo Muro

Reputation: 192

Try this out:

export interface MyInterface {
    myCallback: (length: number) => void;
}

Upvotes: 2

Related Questions