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
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.
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.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With