Home > Enterprise >  Typescript property derived from other properties
Typescript property derived from other properties

Time:10-01

I have a simple class in Typescript which has an id and name properties. I want to have a third property called displayText which concatenates these other two properties.

I know in c# it would look like the following, what's the equivalent syntax in Typescript?

public string DisplayText => Id   " - "   Name

CodePudding user response:

You can create an accessor:

class Person {
    constructor(public name: string, public id: string) {}
    get displayText() { return this.id   " - "   this.name }
}

let p = new Person("Name", "Id")
console.log(p.displayText)

Playground Link

  • Related