"Computed" Property In Typescript


Answer :

If it's an interface then there's no syntax, because all properties in JavaScript can have getter/setter functions instead of being exposed fields. It's an implementation concern.


BTW members in TypeScript use camelCase not TitleCase:


export interface Person {
// get + set:
firstName: string;
lastName : string;
jobTitle : string;

// get-only:
readonly fullName : string;
}

class SimplePerson implements Person {

public firstName: string; // value-property (“field”)
public lastName: string;
public jobTitle: string;

get fullName(): string { // read-only property with getter function (this is not the same thing as a “function-property”)
return this.firstName + " " + this.lastName;
}
}



I note that it is confusing that TypeScript's designers chose to use the keyword readonly to denote "readable" properties in an interface when it doesn't actually prohibit an implementation from also having a property setter - I would have preferred the syntax to be something like readable fullName: string; and readwrite fullName: string; - C#/.NET has the same problem: the IReadOnlyList<T> interface does not mean implementations have to be immutable.



Javascript supports get and set when defining a property (mostly using Object.defineProperty).



Apparently there's an handy syntax for it in typescript (for classes) :



class MyClass{
firstName: string;
lastName: string;

constructor(firstName: string, lastName: string){
this.firstName = firstName;
this.lastName = lastName;
}

get fullName(){
return `${this.firstName} ${this.lastName}`;
}
}


Regarding interfaces, I'm not sure such a thing is possible since their sole purpose is data description not implementation.



You can also define getters and setters in JavaScript.



Try this in your Component Class:



person: Person;
...
// You got the person Object from your Backend API.
...
// Now
get fullName() {
return `${this.person.firstName} ${this.person.lastName}`;
}


And then in your Template:



Simply use fullName like this:



<p>{{ fullName }}</p>


Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android SDK Location Should Not Contain Whitespace, As This Cause Problems With NDK Tools