Create an object inside the class:

class AppComponent { dish = {}; loadDishWindow(){ console.log(this.dish); //->Object {} this.dish = { attributes : [], id : null , name : "", type : null, type_id: null, unit: null, unit_id: null }; console.log(this.dish); //->Object {attributes: Array[0], id: null, name: "", type: null, type_id: null…} } 

Why, if I call console.log(this.dish.name); in this method, instead of the last console.log() , for example, then when compiling it gives an error?

 error TS2339: Property 'name' does not exist on type '{}'. 

I use gulp

    1 answer 1

    why:

     let dish = {}; console.log(dish.name);// ошибка, Ρƒ блюда отсутствуСт имя // Π² ΠΎΠ±Ρ‰Π΅ΠΌ(Π½ΠΎ Π½Π΅ ΠΊΠΎΠ½ΠΊΡ€Π΅Ρ‚Π½ΠΎΠΌ) случаС Ρ€Π΅ΡˆΠ°Π΅Ρ‚ΡΡ интСрфСйсами // https://www.typescriptlang.org/docs/handbook/interfaces.html 

    (hello static typing)

     let число = 78; число = 'строка';// ошибка, Ρ‚ΠΈΠΏ число Π½Π΅ ΠΌΠΎΠΆΠ΅Ρ‚ ΠΏΡ€ΠΈΠ½ΡΡ‚ΡŒ Ρ‚ΠΈΠΏ "строка" 

    decision:

     class AppComponent { // ΠΏΡ€Π΅Π΄ΠΏΠΎΡ‡Ρ‚ΠΈΡ‚Π΅Π»ΡŒΠ½Π΅ΠΉ Ρ‚Π°ΠΊ dish = <any>{}; // Π½ΠΎ ΠΌΠΎΠΆΠ½ΠΎ ΠΈ Ρ‚Π°ΠΊ // dish; //Π² скомпилированном ΠΊΠΎΠ΄Π΅ ΠΎΠ½ Ρ‚ΡƒΡ‚ Π½Π΅ создаётся(см. js) // ΠΈΠ»ΠΈ ΠΊΠ°ΠΊ-Ρ‚ΠΎ Ρ‚Π°ΠΊ interface idish { attributes : string[], id : null | number , name : null | string, type : null | string, type_id : null | string, unit : null | any, unit_id : null | any, }; class AppComponent { dish:idish = <any>{} } 

    upd:
    about null and undefined interestingly write here
    your IMHO voiced here