1

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?

1 Answer 1

2

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;
Sign up to request clarification or add additional context in comments.

2 Comments

The problem with this is that now the observe function doesn't exist, so my addObserver method will have to call observer(...) instead of observer.observe(...)
That is correct. As far as I know, what you want is not possible in TypeScript then.

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.