I think Interface rarely have both anonymous and named function. Is this right?
TypeScript compiler allows interface to have both anonymous and named function.
// no error
interface Foo {
(x: number, y: number): number; // anonymous
namedMethod: (z: string, w: string) => string; // named
}
But it seems unavailable.
// badProp is not assignable
const foo1 : Foo = {
badProp(x: number, y: number) { return 1 },
namedMethod(a: string, b: string) { return 'str'; }
}
// syntax error
const foo2 : Foo = {
(x: number, y: number) { return 1 },
namedMethod(a: string, b: string) { return 'str'; }
}
using any
type, it works.
const temp: any = function (x: number, y: number) { return 1 };
temp.namedMethod = function (a: string, b: string) { return 'str'; }
const foo3: Foo = temp;
Though using both is Technically possible, Interface rarely have both anonymous and named function. Is this right?
An "unnamed" member in a TypeScript interface does not refer to an anonymous member, but declares the function signature of the interfaced class itself, as described in this section of the documentation.
For example:
/**
* Interface for function that takes two numbers as arguments, and returns
* a number.
**/
interface TwoNumberFunction {
(x: number, y: number): number,
}
// simple function: adds two numbers
function add(x: number, y: number): number {
return x + y;
}
// 'add' is a function that takes two numbers and returns a
// number, so it matches the interface's requirements:
const func: NumberFunction = add;
func(1, 2); // = 3
TypeScript allows interfaces to have hybrid types, i.e. interfaces can have a combination of properties, function declarations, indexer and methods. This flexibility is allowed to get aligned with JavaScript dynamic nature.
interface Foo {
(x: number, y: number): number; // anonymous
namedMethod: (z: string, w: string) => string; // named
randomNumber: number
}
const foo2 = ((x: number, y: number) => x+ y + 1) as Foo;
foo2.namedMethod = (z: string, w: string) => z;
foo2.randomNumber = 4
console.log(foo2(1, 3)); // prints 5
console.log(foo2.namedMethod('hello', 'world')); // prints 'hello'
console.log(foo2.randomNumber); // prints 4
Watch this video to know what is hybrid types in typescript?
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