3

Just following the simplest Typescript tutorial and when it comes to typing a function parameter I'm failing.

function greeter(person: string) {
    return "Hello " + person;
}

var user = "Jack";

document.body.innerHTML = greeter(user);

But when I load the page I'm getting "Unexpected token :" - the browser is trying to parse Javascript? I get that Tyescript will compile down to JS, but I'm missing something here.

I'm using Visual Studio 2013, with jQuery.d.ts to type it.

The .ts is going through TypeScriptCompile for its build action.

Body for the .aspx looks like this:

<div>
    <script src="Scripts/Main.ts"></script>
</div>
3
  • 1
    In general .ts files are compiled to .js files. Don't run just the .ts Commented Dec 2, 2013 at 16:07
  • 1
    you need a return type on your function also. since it is returning a string, you need: function greeter(person: string):string { return "Hello " + person; } Commented Dec 2, 2013 at 16:15
  • 2
    Return type annotations are optional; the return type of the function will be inferred from the return statement. Commented Dec 2, 2013 at 18:17

2 Answers 2

4

You are trying to include the .ts file directly, and the browser does not understand that. In this case, it balks on the first type definition it encounters, i.e. the semicolon in

function greeter(person: string) {

What you need to do is compile the Scripts/Main.ts file to a Scripts/Main.js file (VS2013 should do this automatically for you), and then include that in the .aspx source code.

To verify this, there should be a + sign next to the Main.ts file in the solution explorer, and the Main.js file should be under that.

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

2 Comments

Thanks man. I can't see a + to let me expand my .ts, in fact there's no .js in the solution explorer at all, but it does get compiled and is in the file system so including it worked. I'd upvote if I had the rep ;)
@Jack0x539 - perhaps you could turn on the hidden files for your project? You should see the .JS file then...it's just not included in the project.
0

You need to reference the JS file not the TS file:

<div>
    <script src="Scripts/Main.js"></script>
</div>

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.