Home > Net >  Functions in typescript
Functions in typescript

Time:12-24

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

CodePudding user response:

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

CodePudding user response:

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
  • Related