3

Consider this TypeScript code, compiled with 2.6.1:

function foo<T> (bar: T, baz: (T) => void) {
    const test: T = bar;
    baz(test);
}

const string: string = "a";
foo(string, num => num.parseInt());

I would expect the compilation to fail, because the function foo is called with a string, but the passed callback function is using a method that is not available in string -- while the function signature indicates that type of argument in callback function should be the same as the type of the first parameter.

However, the code compiles and then fails in runtime.

What am I missing?

8
  • 1
    "is using a number method" --- there is no parseInt in the Number.prototype. Commented Nov 22, 2017 at 20:18
  • Try foo<string>(...) Commented Nov 22, 2017 at 20:20
  • Try foo(string, (num: string) => num.parseInt()); Commented Nov 22, 2017 at 20:28
  • @zerkms fixed,thank you Commented Nov 22, 2017 at 20:51
  • look at @zerkms comment. If you try foo("a", x => console.log(x.toFixed())) the compiler will tell that the property toFixed does not exist on type string Commented Nov 22, 2017 at 20:51

1 Answer 1

6

Well, because T in baz: (T) => void is not a type name, it's a parameter name.

When you fix the syntax to mean what you want it to mean, you get the expected error:

function foo<T> (bar: T, baz: (t: T) => void) {
    const test: T = bar;
    baz(test);
}

const s: string = "a";
foo(s, num => num.parseInt()); 
// Property 'parseInt' does not exist on type 'string'.

Granted, it's really hard to spot errors like this one - I saw it only when I pasted your code into typescript playground and turned on --noImplicitAny. (T) immediately got highlighted with Parameter 'T' implicitly has an 'any' type. Even that error was puzzling for a moment - wait what - T is not a parameter, it's a type - ...!

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

2 Comments

Relevant FAQ entry
Thanks, this fixed my issue as well!

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.