Home » Javascript » javascript – Typescript error : Function declarations are not permitted in blocks in strict mode

javascript – Typescript error : Function declarations are not permitted in blocks in strict mode

Posted by: admin February 24, 2020 Leave a comment

Questions:

I try to run a script but I have this error : Function declarations are not permitted in blocks in strict mode during targeting of the 'ES3' or 'ES5' version. The modules are automatically in strict mode.

I’m in typescript, here is the script :

export default () => {

  if(document.getElementById("myRange")){
    //slider 
    var slider = document.getElementById("myRange") as HTMLInputElement;
    var output = document.getElementById("demo");
    var gainTimeOutput = document.getElementById("time");
    var sliderEco = document.getElementById("myRange-eco") as HTMLInputElement;
    var outputEco = document.getElementById('demo-eco');
    var eco = document.getElementById('eco');
    outputEco.innerHTML = sliderEco.value;
    output.innerHTML = slider.value;

    function movingSlider(){ <-- Error happens here 
      output.innerHTML = slider.value;
      var convertSlider = parseInt(slider.value); 
      var convertSliderEco = parseInt(sliderEco.value);

      var gainTime = Math.round(convertSlider).toString();
      var gainMoney = (Math.round(convertSlider* 2).toString();

      gainTimeOutput.innerHTML = gainTime + "h"; 
      outputEco.innerHTML = sliderEco.value;
      eco.innerHTML = gainMoney + "€";
    }

    slider.oninput = e => {
      movingSlider()
    };

I don’t get why, the things is that when I delete my if(document.getElementById("myRange")), it works good,
Anyone know why I have this error and how should I fix that ?

How to&Answers:

It’s pretty much just what the error says. You have a function declaration in a block, whose behavior is weird across environments and unpredictable before being specified in ES6, so it’s not permitted by your setup. Assign a function expression to a variable name instead. Change

function movingSlider(){

to

const movingSlider = function movingSlider(){

If you’ve posted the full code of the function being exported, then the code would probably be cleaner and the above wouldn’t be necessary if you simply returned early if myRange doesn’t exist:

export default () => {
  const slider = document.getElementById<HTMLInputElement>("myRange");
  if (!slider) {
    return;
  }
  // rest of your code

This lets you avoid an unnecessary space of indentation throughout the rest of your function.