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")
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.
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.
Interfaces define the specifications of entities and they can be implemented by functions or classes.
Perhaps you are thinking of something like this?
interface FunctionInterface {
(s: string): boolean;
}
const f: FunctionInterface = s => true;
const b: boolean = f('someString');
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With