1

I have been experimenting with OO in typescript lately, and have been trying to declare some generic classes.

I am trying to extend a class, and declare defaulted values inside the class itself, but I am running into a syntax error.

Why would my property be read only in this situation?

    export interface Heading {
      size: number;
      color: number;
    }

    export class text {
      size: number;
      color: number;
    }

    export class Document extends text {
      H1: Heading = {
        size = 1 // syntax error - Cannot assign to 'Number' because it is a constant or a read-only property.
      };
    }

2 Answers 2

2

You have two issues.

First, the color attribute has to be marked as optional if you are going to exclude it.

export interface Heading {
    size: number;
    color?: number;
}

Second, you have to use Object notation : and not equals.

export class Document extends text {
    public H1: Heading = {
        size:  1
    };
}
Sign up to request clarification or add additional context in comments.

Comments

1

If you want your Document to have default values of size and color, you should write the values as they appear in the extended class text:

export class Document extends text {
  size = 1;
  color = 1;
}

By the way, you code had an issue:

TypeScript compiler really says H1 lacks of color property. So, you either add it to your class:

export interface Heading {
  size: number;
  color: number;
}

export class text {
  size: number;
  color: number;
}

export class Document extends text {
  H1: Heading = {
    size: 1,
    color: 1,
  };
}

or place an optional ? operator:

export interface Heading {
  size: number;
  color?: number;
}

export class text {
  size: number;
  color: number;
}

export class Document extends text {
  H1: Heading = {
    size: 1
  };
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.