Search code examples
typescripttypesimplicit-typing

Typescript implicit types (not implicit any)


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?


Solution

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

    enter image description here

    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)
    

    enter image description here

    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.