The closest thing is to override the toString and/or valueOf methods that are inherited from Object.prototype. But: console.log doesn't use those in most implementations, you'd have to do console.log(String(person)) or similar.
For instance, toString:
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
toString(): string {
return this.name;
}
}
Live Example (JavaScript, TypeScript version on the playground):
class Person {
constructor(name, age) {
this.name = name
this.age = age
}
toString() {
return this.name;
}
}
const person = new Person('Jim', 28);
console.log(String(person));
Similarly, if you override valueOf and return a number, then when a numeric operator is used with your instance, it'll use the number valueOf returns:
class Person {
constructor(name, age) {
this.name = name
this.age = age
}
valueOf() {
return this.age;
}
}
const person = new Person('Jim', 28);
console.log(person + 4); // 32
valueOf can return anything (including a string), although if it returns a non-primitive, that object will be converted to a primitive in the usual way for that object.
Side note: You can save yourself some typing by using TypeScript's automatic property declaration:
class Person {
constructor(public name: string, public age: number) {
}
toString(): string {
return this.name;
}
}
The public in the parameter list to the constructor tells TypeScript to create those as public properties and to assign them within the code of the constructor for you.