17

It will complain that type of arg is any

interface Foo { 
  foo(arg: string): void 
}

class FooImpl implements Foo {
  foo(arg) { console.log(arg) }
}

I can of course specify that it's string but it's repetitive.

Maybe there's a way to tune TypeScript to make it infer that it's string automatically?

4
  • Agree, it is a missing feature in TypeScript. However, it is not that simple, as you can implement multiple interfaces with the same foo function with different arguments. Some signature merging is needed. Commented Dec 31, 2017 at 0:44
  • I think the whole "infer" thing does not match with what is typescript being designed for. In typescript everything needs to be strongly typed unlike javascript where you can "assume" the datatype for any variable/arg depending on the declaration. Commented Dec 31, 2017 at 6:40
  • 2
    @Niladri Typescript infers correctly in a whole bunch of quite complicated cases Commented Dec 31, 2017 at 7:50
  • 1
    Possible duplicate of Why is TypeScript unable to infer the type of function parameters when implementing a generic interface? Commented Apr 21, 2018 at 13:47

1 Answer 1

10

Maybe there's a way to tune TypeScript to make it infer that it's string automatically

No. Here is the relevant TypeScript issue with reasons why its not there: https://github.com/Microsoft/TypeScript/issues/1373

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

2 Comments

Digging deeper: github.com/microsoft/TypeScript/pull/… has a more concrete discussion.
There's intent to fix it, eventually: github.com/microsoft/TypeScript/issues/23911

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.