0

Can someone explain how if the below will type to a object that holds 2 functions? I can't find the docs on something like this.

interface FooContext {
  bar(a: A, b: B[]): boolean;
  baz(a: A, b: B[]): boolean;
}
2
  • I'm not sure if I understood your question but hope the following helps: an interface doesn't have objects, it has classes that implements it and these classes will have objects (instances) Commented Mar 18, 2021 at 17:43
  • Doesn't an interface type to an object though? Commented Mar 18, 2021 at 17:46

2 Answers 2

1

If I understood your question correctly, here are three examples of how an interface would resolve into real objects:

interface FooContext<A, B> {
  bar(a: A, b: B[]): boolean;
  baz(a: A, b: B[]): boolean;
}

const example1: FooContext<number, string> = {
    bar(a, b) {return false},
    baz(a, b) {return true}
}

class Example2 implements FooContext<string, number> {
    public bar(a: string, b: number[]) {return false};
    public baz(a: string, b: number[]) {return true}
}

const example2: FooContext<string, number> = new Example2();

//interface that describes a function-object
interface FunctionInterface {
  (): boolean;
}

const example3: FunctionInterface = () => true;

An interface can describe any kind of object, be it an instantiated object of a class or a simple object itself. Keep in mind that arrays, functions, classes, and so on are all objects themself in javascript and can also be described by an interface.

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

1 Comment

You simply assume that the OP actually uses a templated interface? Perhaps types A and B are defined in a completely different way. (You might be right though, but the OP didn't provide that info explicitly.)
1

Your interface FooContext defines two methods: bar and baz. But it also defines the exact signature of those two methods: both the bar and baz functions take two parameters, the first one of type A and the second one of type B[], and they both return a value of type boolean.

Any object that provides at least those two methods with those signatures will comply with your FooContext interface.

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.