[typescript] console.log not working in Angular2 Component (Typescript)

I am relatively new to both Angular2 and typescript. Since typescript is a superset of javascript, I'd expect functions like console.log to work. console.log works perfectly in .ts files when outside a component class but does not work as I'd expect from inside the component class.

// main.ts

import { Component } from '@angular/core';
console.log("Hello1"); //1. This works perfectly

@Component({..)
export class App {
 s: string = "Hello2";
 // console.log(s); //2. This gives compilation error (when uncommented)
 // Error: Function implementation is missing or not immediately following the declaration.
}

Is there anything that I am missing?

This question is related to typescript angular

The answer is


The console.log should be wrapped in a function , the "default" function for every class is its constructor so it should be declared there.

import { Component } from '@angular/core';
console.log("Hello1");

 @Component({
  selector: 'hello-console',
})
    export class App {
     s: string = "Hello2";
    constructor(){
     console.log(s); 
    }

}

Also try to update your browser because Angular need latest browser. check: https://angular.io/guide/browser-support

I fixed console.log issue after updating latest browser.


Examples related to typescript

TS1086: An accessor cannot be declared in ambient context Element implicitly has an 'any' type because expression of type 'string' can't be used to index Angular @ViewChild() error: Expected 2 arguments, but got 1 Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Understanding esModuleInterop in tsconfig file How can I solve the error 'TS2532: Object is possibly 'undefined'? Typescript: Type 'string | undefined' is not assignable to type 'string' Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740] Can't perform a React state update on an unmounted component TypeScript and React - children type?

Examples related to angular

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class error TS1086: An accessor cannot be declared in an ambient context in Angular 9 TS1086: An accessor cannot be declared in ambient context @angular/material/index.d.ts' is not a module Why powershell does not run Angular commands? error: This is probably not a problem with npm. There is likely additional logging output above Angular @ViewChild() error: Expected 2 arguments, but got 1 Schema validation failed with the following errors: Data path ".builders['app-shell']" should have required property 'class' Access blocked by CORS policy: Response to preflight request doesn't pass access control check origin 'http://localhost:4200' has been blocked by CORS policy in Angular7