Reputation: 3725
I'm a TypeScript learner and I'm going through different sources and courses, but I couldn't find out how to make the compiler demand arguments for typed function.
The example is very simple: I have a function that needs two strings firstName
and lastName
and is supposed to return a concatenation of it:
type FuncType = (firstName: string, lastName: string) => string;
const getFullName: FuncType = () => "";
I am conscious of the fact that the function definition is not complete. But at this point (of writing the function definition) I would expect the compiler to warn me (or hint me) that I'm missing to specify two parameters (firstName
and lastName
) which are obviously required judging from the type FuncType
.
That is not the case. What am I missing?
Upvotes: 3
Views: 428
Reputation: 14171
As weird as this may seem this is a TS feature. You can read some more about how functions are compared in TS here.
In short TS allows for assignment of functions that have less parameters than the assignable type. The TS wording for this is discarding parameters.
The reason for this is how JS is used. There are a lot of APIs, some related to array, that allow for setting callbacks that have less parameters. If TS would impose this then a lot of existing code would break.
The main reason for this is that JS accepts optional parameters by default, so a function that has less parameters is always assignable to one that has more.
A note: if you actually call the function then TS will kick in as seen here
Upvotes: 4