Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Imported class static fields are undefined

I'm trying to figure out the diff between static fields vs method behavior in classes in typescript and angular. help will be much obliged :)

I have exported class with static fields and methods in app src, when i import it and try to use the static fields they are undefined, if i call static methods they work.

src/app/core/colors.ts

   export class SystemColors {

    static  _gray: {
        default: '#ABAFBE',
        darker: ['#7C8298', '#606473'],
        lighter: ['#C8D1DA', '#E2E3ED', '#F5F6FA']
    };


    public static get gray() {
        return {
            default: '#ABAFBE',
            darker: ['#7C8298', '#606473'],
            lighter: ['#C8D1DA', '#E2E3ED', '#F5F6FA']
        };
    }
}

src/app/app.component.ts

import {SystemColors} from '...';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit, AfterViewInit {

    constructor() {}

    ngOnInit() {
        console.log(1, SystemColors.gray); // static get method has value
        console.log(2, SystemColors._gray); // static field undefined :(
    }
}

like image 440
yael kfir Avatar asked Oct 29 '25 14:10

yael kfir


1 Answers

  static _gray: {
    default: '#ABAFBE',
    darker: ['#7C8298', '#606473'],
    lighter: ['#C8D1DA', '#E2E3ED', '#F5F6FA']
  };

This means "the class has a static property named _gray, who's type is [insert object here]". No value is actually assigned to it though, just a type. Since type information is removed when transpiling, this all goes away. Instead, you want to do this, with an equals sign instead of a colon:

 static _gray = {
    default: '#ABAFBE',
    darker: ['#7C8298', '#606473'],
    lighter: ['#C8D1DA', '#E2E3ED', '#F5F6FA']
  };

With this modified code, you're assigning an actual object to it, not just defining types. This creation and assignment of an object will still happen after the code is transpiled to javascript.

like image 155
Nicholas Tower Avatar answered Oct 31 '25 05:10

Nicholas Tower