Home > other >  let numInArray: number[ ] = [ ]; Gives this ERROR " SyntaxError: Unexpected token ':'
let numInArray: number[ ] = [ ]; Gives this ERROR " SyntaxError: Unexpected token ':'

Time:01-25

I am trying to automatically fill an empty array with numbers from 1 to 100 and then give the output if the following conditions are true:

  1. Print number if it is not divisible by 3 and 5.
  2. If number is divisible by 3 then print Fizz.
  3. If number is divisible by 5 then print Buzz.
  4. If number is divisible by both 3 and 5 then print FizzBuzz.
let num: number | string [] = [];

for (let i=1; i<=100; i  ){
    if ( i % 3 == 0 && i % 5 !== 0 ) {
        num.push("Fizz");
    } if ( i % 3 !== 0 && i % 5 == 0 ){
        num.push("Buzz");
    }  if ( i % 3 == 0 && i % 5 == 0 ){
        num.push("FizzBuzz");
    } if ( i % 3 !== 0 && i % 5 !== 0 ) {
        num.push(i);
    }
}

console.log(num);

I have run the same code in JavaScript without declaring type of num (i.e, num: number | string []) and the code is running fine but when I am running it in TypeScript it is giving the following error.

└─$ node test.ts 
/home/ahmed/Tutorials/JavaScript/test.ts:1
let num: number | string [] = [];
       ^

SyntaxError: Unexpected token ':'
    at Object.compileFunction (node:vm:360:18)
    at wrapSafe (node:internal/modules/cjs/loader:1088:15)
    at Module._compile (node:internal/modules/cjs/loader:1123:27)
    at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
    at Module.load (node:internal/modules/cjs/loader:1037:32)
    at Module._load (node:internal/modules/cjs/loader:878:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:23:47

Node.js v18.12.1

CodePudding user response:

To run the typescript file you need to run the below command and then it will generate a javascript file and you can run that js file.

tsc test.ts
  • Related