Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functions in typescript

Why no missing error ?

interface User {
  // way 1
  foo(): string;  
  foo2(x:number): string; 

  // way 2
  normal: () => string;
  normal2: (x:number) => string;
}

let user: User = {
  // way 1
  foo: () => '',
  foo2: () => '', // why no error since x is missing
  
  // way 2
  normal: () => '',
  normal2: () => '', // why no error since x is missing
};

See this Typescript Playground

like image 291
umesh kadam Avatar asked Dec 24 '21 05:12

umesh kadam


People also ask

What is a function in TypeScript?

Functions are the fundamental building block of any application in JavaScript. They're how you build up layers of abstraction, mimicking classes, information hiding, and modules. In TypeScript, while there are classes, namespaces, and modules, functions still play the key role in describing how to do things.

Can TypeScript types have functions?

In TypeScript, there are multiple syntaxes for declaring the type of a function: Method signatures. Function type literals. Object type literals with call/construct signatures.

What are different ways to write functions in TypeScript?

Writing a function in TypeScript is similar to writing them in JavaScript but with added parameters and return type. Note that any JavaScript function is a perfectly valid TypeScript function. However, we can do better by adding type.

What is the => in TypeScript?

In a type position, => defines a function type where the arguments are to the left of the => and the return type is on the right. So callback: (result: string) => any means " callback is a parameter whose type is a function.


2 Answers

If you invoke (x:number)=>string without passing in x, you get An argument for 'x' was not provided. error.

BUT THIS IS NOT WHAT YOU ARE DOING

What you are doing is assigning ()=>string to (x:number)=>string, which is valid. When you assign ()=>string to (x:number)=>string, the compiler ask: can ()=>string behave the same as (x:number)=>string?

i.e. can ()=>string takes in a number and spit out a string, just like what (x:number)=>string do?

The answer is yes, ()=>string technically can take in any number, but just ignoring it, then return a string, independent of what number it take in. Therefore, ()=>string is assignable to (x:number)=>string

like image 152
Ricky Mo Avatar answered Oct 12 '22 17:10

Ricky Mo


A lower-arity function is assignable to a higher-arity one as long as its return type is compatible and the parameters which are present are compatible.

In your case, because the functions have no parameters and return a string, they are compatible.

TS Playground

type NumFn = (n: number) => string;
declare const isCompatible: (() => string) extends NumFn ? true : false; // true
like image 3
jsejcksn Avatar answered Oct 12 '22 17:10

jsejcksn