简体   繁体   中英

Typescript Inerfaces Uncaught TypeError: Cannot set property

I am trying to add Type Assertion to the object, I am facing a TypeError during assigning a value to the nested object.

Here is snippet

interface Person {
    age: number;
    name: string;
    study: {
        schoolName: string
    }
}

let john = {} as Person;

john.age = 25;
john.name = 'John';
john.study.schoolName = 'some school';

console.log(john); // Uncaught TypeError: Cannot set property 'schoolName' of undefined

Link for the Typescript playground Link

Maybe looking at the compiled version of your snippet will clear it out for you

var john = {};
john.age = 25;
john.name = 'John';
john.study.schoolName = 'some school';
console.log(john);

As you see Typescript does not actually initialize the study property.

Because interface doesn't actually "create" your object. In your code before you start assigning values john is just empty object. You can assign properties to it (age, name,...), because that is something normal. You are trying to assign a property to an object property that doesn't exist. Either use class and initialize it using a constructor. Or have a function that creates objects from that "interface" correctly.

Basically interface is just a fancy thing in typescript to prevent typos, etc from developers. It doesn't create anything behind the scene.

Typescript will only tell your IDE what types this new object has. It will not create a full object for you.

Here is how you want to create the object:

interface Person {
    age: number;
    name: string;
    study: {
        schoolName: string
    }
}

let john = {} as Person;

john.age = 25;
john.name = 'John';
john.study = { 
    schoolName: 'some school'
};

console.log(john); 

alternatively you can directly do this:

let john: Person = {
    age: 25;
    name: 'John';
    study: {
        schoolName: 'some school'
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM