Reputation: 6202
I'd like to use Java-style functional interfaces in TypeScript. Meaning, I'd like to have an interface with exactly one method, and I'd like to be able to supply just the method wherever that interface is expected. Here's what I've tried:
interface Observer<T> {
observe(t: T);
}
function addObserver<T>(observer: Observer<T>) {
// calls observer.observe at some point
}
// works
addObserver({
observe: t => console.log(t)
});
// Property 'observe' is missing
addObserver(t => console.log(t));
How do I accomplish this in TypeScript?
Upvotes: 1
Views: 1891
Reputation: 3937
Functional interfaces in Java are only needed because the language has no first class functions.
Javascript has (and thus typescript has, too). That means that, to be idiomatic, you should not try to emulate the Java way but just use functions directly.
To express that in typescript, the language has function types (see section "Function Types" in the handbook).
Applied to your example, that would look like this:
interface Observer<T> {
(t: T): void;
}
You could also use a Type Alias (see section "Type Aliases" in the handbook)
type Observer<T> = (t:T) => void;
Upvotes: 2