TypeScript, what are call signature of an object literal and how can they be used with generic types? TypeScript, what are call signature of an object literal and how can they be used with generic types? typescript typescript

TypeScript, what are call signature of an object literal and how can they be used with generic types?


Functions can have properties, that's what the object literal syntax is for: it allows to define a call signature and additional properties. Your two examples are equivalent because the second doesn't define additional properties on the object literal. You can read more on that in the section on hybrid types.

Additionally, the object literal allows to define multiple call signatures for function overloads. You can create an object of such an interface with Object.assign:

interface Foo {    (x: string): number,    (x: number): string,    bar: Array<any>,}const foo: Foo = Object.assign(function (x: any) {    if (typeof x === 'string') {        return parseInt(x);    } else {        return x.toString();    }}, {    bar: []});


It is because Function in JavaScript is also an object.

Consider the following:

function foo() { return 'foo' }// vsconst foo = Object.assign(  function () { return 'foo' },  {})

TypeScript just follows what is possible in JavaScript.


I have exact the same confusion when I read this example in typescript handbook.

Now I understand it like this, but not very sure:

interface MyFunc {    (arg: string): string //define a function by a call signature}let myIdentity: MyFunclet myIdentity2: {     (arg: string): string //here is the body of MyFunc, the call signature} //the total is a call signature in an object literal typemyIdentity = identitymyIdentity2 = identity

So there are two function definition format:

interface MyFunc {    (arg: string): string //a call signature    funcName: (arg: string) => string //express of function in object literal}