Umesh Kadam
Umesh Kadam

Reputation: 1181

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

Upvotes: 4

Views: 266

Answers (3)

Neveen Atik
Neveen Atik

Reputation: 151

Just like the answers above seems like it can only be detected when you call the function without arguments my bet is it is something to do with typescript contextual typing (I too am learning here)

Function parameters are checked one at a time, with the type in each corresponding parameter position checked against each other. If you do not want to specify types at all, TypeScript’s contextual typing can infer the argument types since the function value is assigned directly to a variable of type SearchFunc. Here, also, the return type of our function expression is implied by the values it returns typescript handbook

interface Counter {
  (start: number): string;
  interval: number;
  foo: (x:number) => string;
  bar(x:number):string;
  reset(): void;
}

function getCounter(): Counter {
  let counter = function (s...

Playground Link

Upvotes: 0

Ricky Mo
Ricky Mo

Reputation: 7718

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

Upvotes: 3

jsejcksn
jsejcksn

Reputation: 33881

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

Upvotes: 3

Related Questions