1

I've got an input element which tries calling a typescript function during the onchange event. However it doesn't work and I get the following error: inputChange is not defined. In my main.ts file, I've got a simple function called inputChange which just console logs "Hello World!".

// index.html    
<input onchange="inputChange()"/>

// main.ts
function inputChange(){
    console.log('Hello World!')
}

Does anyone know how I can access functions like inputChange from my index.html file? (Also everything else in my main.ts file works as normal but for some reason I can't access typescript functions/variables from index.html)

I'm using webpack and babel to compile the typescript file into a bundle.js which is then appended into my index.html file by HTMLWebpackPlugin.

This is my tsconfig file:

{
    "compilerOptions": {

        /* Basic Options */
        "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
        "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
        "lib": ["es6","dom"],                             /* Specify library files to be included in the compilation. */
        "allowJs": false,                       /* Allow javascript files to be compiled. */
        "sourceMap": true,                     /* Generates corresponding '.map' file. */

        /* Strict Type-Checking Options */
        "strict": true,                           /* Enable all strict type-checking options. */
        "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */
        "strictNullChecks": true,              /* Enable strict null checks. */
        "strictFunctionTypes": true,           /* Enable strict checking of function types. */
        "strictBindCallApply": true,           /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
        "strictPropertyInitialization": true,  /* Enable strict checking of property initialization in classes. */
        "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
        "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */

        /* Additional Checks */
        "noUnusedLocals": false,          /* annoying when just testing */                // "noUnusedLocals": false,                /* Report errors on unused locals. */
        "noUnusedParameters": false,      /* annoying when just testing */                 // "noUnusedParameters": true,            /* Report errors on unused parameters. */
        "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
        "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */

        /* Module Resolution Options */
        "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
        "esModuleInterop": true,                  /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */

        /* Advanced Options */
        "skipLibCheck": true,                     /* Skip type checking of declaration files. */
        "forceConsistentCasingInFileNames": true  /* Disallow inconsistently-cased references to the same file. */
    },
    "compileOnSave": true,
    "exclude": ["node_modules"],
    "include": ["./public"]
}
2
  • hi are you compiling (transpiling) your main.ts file ina. main.js file? and link it to your index.html page? Commented Aug 19, 2020 at 8:38
  • Yes I am. I'm using webpack with babel and HTMLWebpackPlugin to insert a bundle.js into my index.html file Commented Aug 19, 2020 at 8:49

1 Answer 1

2

This is one of the many reasons not to use onxyz-attribute-style event handlers: They require that the function you use has to be a global. It sounds like you have TypeScript set up to use modules, so top-level declarations in TypeScript files aren't globals.

Instead, hook up the handler to the input using JavaScript, identifying the input via where it is in the DOM, its class, or its ID. For instance, here's an example using an ID:

<input id="the-input">

and in your TypeScript code in the module where inputChange is defined (or another module that imports it):

document.getElementById("the-input").addEventListener("change", inputChange);
Sign up to request clarification or add additional context in comments.

2 Comments

How would I setup Typescript to not use modules? I feel like my small project would benefit from having global variables. Also my project will have about 30 input fields many of which have overlapping functionality, thus I preferably would like to use the onxyz-aattribute-style event handlers to make my code less verbose.
@user8380672 - The documentation says it's "module": "none" in your tsconfig.json. But the global namespace is very crowded, it's easy to waste time fighting bugs caused by conflicts. If you have 30 inputs with overlapping functionality, you can almost certainly handle that better with event delegation and classes than with onxyz-attribute handlers. But of course, it's your project. :-) Happy coding!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.