简体   繁体   中英

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.)

Try this out:

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM