Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 138134

Calling a function defined in a TypeScript file from an HTML input onchange attribute

$
0
0

If I had a JavaScript index.js file like this:

function foo(val) {
  console.log(val);
}

and a index.html HTML file like this:

...
<script src="./index.js"></script>
<div id="container">
  <label>bar
    <input type="radio" name="radio" value="bar" onchange="foo(value);"/>
  </label>
  <label>baz
    <input type="radio" name="radio" value="baz" onchange="foo(value);"/>
  </label>
...

this would log bar or baz as I check a radio button.

I want to call foo(value) which is defined in a index.ts TypeScript file like this:

let foo = (value: string): void => {
  console.log(value);
};

In index.html I change <script src="./index.js"></script> to <script src="./src/index.ts"></script>, then I use parcel to build the app, but the resulting built file is not able to call the function, logging referenceError: setLayer is not defined.

I know that in theory the browser does not know anything about TypeScript and only knows JavaScript, but after compiling with parcel in my dist dir I see a bunch of *js files, one of which I thought might have included the compiled foo() function.

So the question is: how can I call a function inside a TS file from a HTML input onchange attribute like I would do with a JS file?

Last but not least: to build my app I invoke parcel start (or even parcel run build), and my package.json looks like this:

{
  "name": "app_test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\"&& exit 1",
    "start:build": "tsc -w",
    "start": "parcel index.html",
    "build": "parcel build --public-url . index.html"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
  },
  "devDependencies": {
    "parcel-bundler": "^1.12.4",
    "typescript": "^3.7.5"
  }
}

Viewing all articles
Browse latest Browse all 138134

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>