Error message encountered when attempting to invoke a function in a TypeScript file due to an undefined module

Here is an example of code from my Index.ts file, which has a reference to sample.ts:

/// <reference path="sample.ts" />
var s: sample.Calculate = new sample.Calculate(5, 5); -- encountering an error
s.alertme();

This is the content of my Sample.ts file:

    module sample {
     export class Calculate {
        constructor(public x: number, public y: number) {
            console.log(x + y);
        }

        alertme() {
            alert('ok');
        }
    }
}

I am facing an error when calling the calculate function. Here's what it looks like: https://i.sstatic.net/hLq77.png

PS: I am utilizing visual studio 2015. HTML:

    @{
    ViewBag.Title = "Home Page";
}

<div class="jumbotron">
    <h1>MVC</h1>
    <p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
    <p><a href="http://asp.net" class="btn btn-primary btn-lg">Learn more &raquo;</a></p>
</div>

<div class="row">
    <div class="col-md-4">

    </div>
</div>
@section scripts{    
    <script src="~/Scripts/typings/Index.js"></script>
}

Answer №1

It appears that the Sample.js file is not being loaded in the browser, causing the sample module to not be loaded as well.

From the code provided, it seems like you intend to load the scripts using script tags instead of a module system. If that's the case, all you need to do is:

@section scripts{
    <script src="~/Scripts/typings/Sample.js"></script>
    <script src="~/Scripts/typings/Index.js"></script>
}

You mentioned using requirejs, so if you meant to use that, you will need to include the following:

// Sample.ts 
export module sample {
    ...
}

// Index.ts
/// <reference path="sample.ts" />
import sample = require('./Sample');
var s: sample.Calculate = new sample.Calculate(5, 5); // should work correctly

Don't forget to add the "amd" module to your compiler options.
For more information, check out the Modules section of the documentation.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Avoiding non-router links from remaining active while using routerLinkActive in Angular

One component in the list item of the navigation bar caught my attention: <div [routerLink]="link" routerLinkActive="bg-blue-100" class="flex w-[80%] mx-auto p-3 rounded-md font-bold text-xl justify-between items-center gr ...

Explain the significance of the symbols $$ and $ in the context of webdriver, and provide instructions on integrating them into

According to the webdriver documentation, using the $ and $$ functions in WebdriverIO can provide shortcuts for moving deeper into the DOM tree without relying on complex xPath selectors. Currently, I am working on writing a cucumber test for my Reactjs a ...

Error encountered: Denied access in AWS Transcription Node JS API

I have been working with the AWS transcription API in Node JS and my code looks like this: const tClient = new TranscribeClient({ region: "us-east-1", credentials: { accessKeyId: AWS_ID, secretAccessKey: SECRET, ...

ESLint error caught off guard by function expression in customized MUI Snackbar Component with Alert

Struggling to create a personalized MUI Snackbar using the MUI Alert example from the official Documentation, but facing ESlint errors: error Unexpected function expression prefer-arrow-callback error Prop spreading is forbidden react/jsx-props-no-s ...

Custom time selector does not automatically set the default value

After creating two inputs where one represents hours and the other minutes, clicking on edit should display the total time in seconds. The original time for editing should remain unchanged until you choose to save it. Here is the link to the code: https:// ...

Does anyone have knowledge of any existing sample code for a .NET OpenID Provider?

Looking to develop an OpenID Provider in .Net and curious if there are any existing OpenSource code libraries that I can utilize? ...

Error: The array provided to THREE.BufferAttribute must be a Typed ArraydataType

I am attempting to generate a point cloud using threejs with the following code: const pcGeom = new THREE.BufferGeometry(); const rows = 100; const columns = 3; const vertices = [...Array(rows)].map(() => [...Array(columns)].fill(0)); for(let i = 0; i & ...

Enhancing class functionality with decorators in TypeScript

Over on the TypeScript's Decorator reference page, there is a code snippet showcasing how to override a constructor with a class decorator: function classDecorator<T extends {new(...args:any[]):{}}>(constructor:T) { return class extends con ...

How to attach keypress event to an input with type 'number' using Jquery and attribute value

I'm trying to figure out how to validate an input field only when it is of type number and has the validate attribute set to checkit. I'm not sure what to use in place of the asterisks to bind this to the keypress event $('*** input[type=num ...

I possess a JSON array object and need to identify and extract the array objects that contain a specific child node

const jsonArray = { "squadName": "Super hero squad", "homeTown": "Metro City", "formed": 2016, "secretBase": "Super tower", "active": true, "members": [ { "name": "Molecule Man", "age": 29, "secretIdent ...

NgbHighlight now allows for one highlight element per line

I am currently utilizing NgbHighlight to allow users to search within a list. However, I am facing an issue with the highlighting of search results. My intention is to highlight only the first match in the list. I am sticking to the basic implementation ...

Combining two sets of data represented by IEnumerable of IEnumerable of strings with distinct columns

My table\grid class is defined by two properties: public class MyTable { public IEnumerable<string> Columns {get;set;} public IEnumerable<IEnumerable<string>> Rows {get;set;} } Let's say we have a table\grid wit ...

Authentication - The success callback of $http is executed rather than the error callback

I seem to be facing an issue with authentication in a MEAN stack app, possibly due to my limited understanding of promises and the $http's .then() method. When I try to authenticate to my backend Node server with incorrect credentials, the success cal ...

What is the best way to make an input text the focus when an item on a dropdown menu is clicked?

I have a website with a dropdown menu and an input box. I want the user experience to be more seamless by automatically focusing the mouse cursor inside the input box when they click on an option in the dropdown menu. This way, users can start typing right ...

Generate a dynamic vertical line that glides smoothly over the webpage, gradually shifting from one end to the other within a set duration using javascript

I have designed a calendar timeline using html. My goal is to implement a vertical line that moves from left to right as time progresses, overlaying all other html elements. This functionality is similar to Google Calendar's way of indicating the curr ...

Tips for simulating a dropdown selection from a remote location

I have multiple dropdown selection menus where changing the option in one menu affects the options in the next menu, and so on. I want to programmatically trigger a change (without user interaction) in the dropdown menu that will activate the JavaScript f ...

What is the most effective method for creating a dynamic XML file for a web service?

In order to create a sizable XML file (around 500 lines) for my web service component, I am considering various approaches. These options include: 1. Utilizing StringBuilder 2. Using the XmlWriter class 3. Implementing a C# object with serialization Which ...

Organizing your code with precision

I'm struggling with a project due to the poorly formatted code, making it almost impossible to read. Despite my attempts with various plugins and tools in VIM, Netbeans, Sublime Text 2, and Eclipse, the situation only seems to worsen. If anyone has ...

Show the day of the week

I'm seeking a solution to display the upcoming Friday of each week within Wordpress. We were able to achieve this in the past using the code below on non-Wordpress platforms, but it seems outdated and no longer functional. For example: This week&apos ...

The error message "Unexpected token var Node.js" means that there is a syntax error

Currently, I am dealing with Node.js and attempting to present a chart that is created from coordinates in a txt file uploaded to the server. However, I am facing an issue where everything works perfectly when I upload the file on the web page except for t ...