atamata
atamata

Reputation: 1077

Typescript property derived from other properties

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

Upvotes: 1

Views: 420

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249546

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

Upvotes: 1

Related Questions