简体   繁体   中英

Typescript - Class (with constructor) that extends an interface (no constructor)

I have an interface that looks like:

interface Person {
  id: number
  name: string
}

I have a class that implements this interface:

class PersonClass implements Person {
  id: number = 123
  name: string = 'Kevin'
}

The above works fine, but is hardcoded. Instead, I want the values to be initialized when the class is created. For example:

class PersonClass implements Person {
  constructor(id, name) {
    this.id = id,
    this.name = name
  }
  id = this.id       // ERROR: Property 'id' is used before its initialization.
  name = this.name   // ERROR: Property 'name' is used before its initialization.
}

As shown above I get an error when trying to use a constructor.

What I want from all of this is to be able to create new instances of PersonClass and initialize its values at that time:

// Should be successful
new PersonClass(1, 'Sandra')  

// Should trigger an error
new PersonClass('McDonalds', 'Fries')

What am I doing wrong / missing?

Try

class PersonClass implements Person {
    id: number;
    name: string;
    constructor(id: number, name: string) {
        this.id = id;
        this.name = name;
    }
}

Or even:

class PersonClass implements Person {
    constructor(public id: number, public name: string) { }
}

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