SirCheckmatesalot SirCheckmatesalot - 2 months ago 20
TypeScript Question

Typescript: Class within Class

I have a class Moviecharacter which represents json data about movie characters aswell as an actor class which holds information about actors.
I want to add the Actor class into my Moviecharacter class without using duplicated attributes:

My versions for Actor and MovieCharacter are:

// actor class stores general information about an actor in a json file
export class Actor{
name: string;
id: number;
}

// duplicated attributes name and id:
export class MovieCharacter {
name: string;
id: number;
character: string;
}


But i want something like this:

// without duplicated Attributes:
export class MovieCharacter {
Actor(); // not working
character: string;
}


Any help would be appreciated.

Answer

// without duplicated Attributes:

Suspect you are looking for inheritance:

// actor class stores general information about an actor in a json file
export class Actor {
    name: string;
    id: number;
}

// Inherits name and id from Actor
export class MovieCharacter extends Actor {
    character: string;
}

More

Some helpful docs : https://basarat.gitbooks.io/typescript/content/docs/classes.html

Comments