Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to implement a function interface in TypeScript?

Tags:

typescript

I would like to be able to do this

class MyFunc extends ((s: string) => boolean) { ... }

so that an instance of MyFunc can be used as a function which takes a string as input and returns a boolean as follows:

const f = new MyFunc();
const b: boolean = f('someString');

Is this possible in TypeScript?

In languages such as Scala, one can extend the type String => Boolean, and provide an apply method to achieve this.

class MyFunc extends (String => Boolean)
val f = new MyFunc()
val b: Boolean = f("someString")
like image 254
Yuhuan Jiang Avatar asked Mar 16 '17 17:03

Yuhuan Jiang


People also ask

How would you implement an interface function in TypeScript?

For example:interface myFunction { // Specify only parameters and return type: (a: string, b: Boolean, c: number): string; } const myFunc: myFunction = (x, y, z) => { return `x is ${x}, y is ${y}, z is ${z}` } // TypeScript will correctly infer "a" to be number, // "b" to be string and "c" to be boolean.

Can an interface have a function TypeScript?

A TypeScript Interface can include method declarations using arrow functions or normal functions, it can also include properties and return types. The methods can have parameters or remain parameterless.

Can you implement a function in an interface?

Interfaces define the specifications of entities and they can be implemented by functions or classes.


2 Answers

Perhaps you are thinking of something like this?

interface FunctionInterface {
    (s: string): boolean;
}

const f: FunctionInterface = s => true;
const b: boolean = f('someString');
like image 200
David Sherret Avatar answered Oct 05 '22 05:10

David Sherret


There is no default apply concept in TypeScript, but there are ways of creating typed objects that are also functions.

interface MyCallable {
    (param1: string, param2: number): string;

    prop1: string;
    prop2: number;
    extraMethod: (param1: boolean) => boolean;
}

function makeMyCallable(prop1: string, prop2: number): MyCallable {
    let that = ((param1: string, param2: number) => param1 + param2) as MyCallable;

    that.prop1 = prop1;
    that.prop2 = prop2;
    that.extraMethod = (param1: boolean) => !param1;

    return that;
}

let mc = makeMyCallable("3", 4);

mc("3", 4);
mc.prop1 = "string";
mc.prop2 = 5;
mc.extraMethod(false);
like image 22
y2bd Avatar answered Oct 05 '22 05:10

y2bd