Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does TypeScript Interface have anonymous and named function?

Tags:

typescript

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?

like image 432
onion mk2 Avatar asked Dec 11 '16 03:12

onion mk2


2 Answers

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
like image 163
Frxstrem Avatar answered Oct 05 '22 02:10

Frxstrem


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?

like image 28
anonymous Avatar answered Oct 05 '22 00:10

anonymous