Using TypeScript with an inline server-side `<script>` block and ASP.Net Using TypeScript with an inline server-side `<script>` block and ASP.Net typescript typescript

Using TypeScript with an inline server-side `<script>` block and ASP.Net


The short answer is no.

You could write a TypeScript file and paste the compiled JavaScript in, but that's as close as you'll get. One practical problem would be that if the compiler transformed your TypeScript into JavaScript, you would lose your TypeScript code. This is why you have a TypeScript file and a JavaScript file.

What's the compelling reason to put the script inline rather than referencing an external script - maybe there is another solution to your problem that doesn't require inline scripts?


You could create a server-control that compiles the code at runtime, and caches it:

[DefaultProperty("Text")]  [ToolboxData("<{0}:TypeScript runat=server></{0}:TypeScript>")]  public class TypeScript : WebControl  {      public string Text { get; set; }    protected override void RenderContents(HtmlTextWriter output)      {          output.AddAttribute(HtmlTextWriterAttribute.Type, "text/javascript");          if (!string.IsNullOrEmpty(this.ID))        {            output.AddAttribute(HtmlTextWriterAttribute.Id, this.ID);          }        output.RenderBeginTag("script");        output.Write(CompileToJavaScript(Text));        output.RenderEndTag();    }    private string CompileToJavaScript(string typeScript)    {        // TODO: Call tsc with the code, and return the result.    }} 

You might be able to compile tsc.js with JScript.NET, if you care to implement the IO-layer, and weed out some JScript.Net (not JavaScript) syntax errors.


  • have a work around for it, what I do is declare the variables needed from razor in a script tag

    <script type="text/javascript">//Razor variables initialized here and declared in the TypescriptFile.ts filevar url = "@Url.Action("NewRequest", "Request")";</script>
  • next declare the url variable in the Typescript file

    //TypescriptFile.tsdeclare var url: string;alert(url);
  • use it

  • sad to see that Visual Studio 2013 still does not provide server side support.