-1
function foo(a: number, b: string): string {
    return a + b;
}

whether I put this in TypeScript playground or VS Code gets a 1068: Unexpected token. A constructor, method, accessor, or property was expected.

Once I make that into a standard TS method signature (by removing the function keyword), everything is fine.

Yet the latest documentation on TypeScript:

https://www.typescriptlang.org/docs/handbook/functions.html

Shows function is totally usable. Very strange.

7
  • Works fine here when tring that exact snippet on typescriptlang.org/play Commented Jan 21, 2019 at 22:32
  • Yep: typescriptlang.org/play/… Commented Jan 21, 2019 at 22:34
  • 1
    If you are inside a class then function is not allowed. But that hold true for es2015 classes as well.. Commented Jan 21, 2019 at 22:35
  • Yes, standalone function works, but within a class definition not. [link]typescriptlang.org/play/… Commented Jan 21, 2019 at 22:36
  • Yep, that is exactly how it works. Inside a class you don't use the function keyword and outside of it you need it. Commented Jan 21, 2019 at 22:40

1 Answer 1

2

This is an example that shows the error you are getting:

class Foo {
  // ERROR unexpected token
  function foo(a: number, b: string): string {
    return a + b;
  }
}

This is invalid TypeScript because, it is invalid JavaScript. e.g. the following is invalid:

enter image description here

Just another example of TypeScript allows you to write JavaScript more safely 🌹

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

Comments

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.