Reputation: 10442
In a Typescript project I worked on that I don't have access to anymore, I remember seeming to be able to do the following:
const fn = string => console.log(string)
Being new to Typescript, it seemed to be the equivalent of writing this:
const fn = (string:string) => console.log(string)
Basically, in my mind, if I named a variable in a function after a native type, it would seem to implicitly be typed as that type, not as any
.
I was very new to Typescript at the time though so it's totally possible something else was really going on and I was just misinterpreting the situation.
Now that I am trying to set up my own typescript project, I would like to configure it to allow that functionality again. I'm not sure how to though or if what I'm thinking of is even a real Typescript feature.
Is this a real feature in Typescript?
If it is, how do I configure Typescript to do this?
Upvotes: 0
Views: 873
Reputation: 1839
Basically, in my mind, if I named a variable in a function after a native type, it would seem to implicitly be typed as that type, not as
any
.
This is entirely wrong. Typescript does not have such a feature. If you do not mention a type, Typescript will simply consider it as any
. This is the same thing happening in the code below.
const fn = string => console.log(string)
string
variable is of any
type. If you have a modern IDE it would show you the same thing if you hover over it.
To give it a type, you have to specifically mention a type, just like in the latter code you added.
const fn = (string:string) => console.log(string)
Is this a real feature in Typescript?
If it is, how do I configure Typescript to do this?
It is not and thus you can't configure it to work that way normally.
Upvotes: 3
Reputation: 31
The closest feature to what you're describing is called Contextual Typing or Type Inference. You can look it up in TypeScript's documentation for more details.
As for the example you have given, the standard (node) definition of console.log
is expecting message
param to by of any
type. That's why in this case your string
parameter infers to any
type.
// src: node_modules/@types/node/globals.d.ts
interface Console {
// ...
/**
* Prints to `stdout` with newline
*/
log(message?: any, ...optionalParams: any[]): void;
// ...
}
Upvotes: 1