2

I have a function which only accepts a number variable.

function add(n1: number) {
    return n1 + n1;
}

And I initialize an any variable and assign it a string of '5'

let number1;
number1 = '5';

I was wondering, why doesn't it show an error when I want to pass a string to the function?

console.log(add(number1));

(Of course it outputs 55, because the string is concatenated.)

4
  • 2
    I'm getting the expected error. Where specifically in the overall process are you checking for this error? The resulting JavaScript is still JavaScript and will still run without complaining about types. It's only in the linting/transpiling that it will show an error. Commented Aug 3, 2021 at 19:34
  • 1
    @David That's weird. I'm running TS v4.3.5 and it doesn't show up on my IDE nor in the compiler: snpy.in/7hkYM1 Commented Aug 3, 2021 at 19:37
  • 1
    I just learned something new from the answer below. The website I was using had noImplicitAny selected. Go into the config and de-select it and the behavior you describe is observed. Commented Aug 3, 2021 at 19:39
  • @David Just checked that and that was the problem. Thanks for pointing out :) Commented Aug 3, 2021 at 19:39

1 Answer 1

2

If the type is not specified (implicit any) or set to any, the uses of the variable won't be type-checked. This is useful if you gradually migrate JavaScript code to TypeScript.

If you want to flag implicit any's (like the one in your example) as error, use the noImplicitAny compiler flag.

Sign up to request clarification or add additional context in comments.

1 Comment

Yep. This is what I was looking for. I just followed along a tutorial and experimented on my own. Didn't get to the tsconfig file yet.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.