sebjwallace
sebjwallace

Reputation: 795

typescript - default value of a class instance

I was wondering if this feature exists in Typescript:

If I had a class

class Person {
  name: string
  age: number
  constructor(name, age){
    this.name = name
    this.age = age
  }
}

and I wanted it to return some default value when the instance is called

const person = new Person('Jim', 28)
console.log(person)
//> Jim

How would I achieve returning a custom/default value if the instance is called without accessing its properties or methods? Is there a keyword that could make a property act this way? I might imagine a 'default' keyword, but is there something similar?

class Person {
  default name: string
  age: number
  constructor(name, age){
    this.name = name
    this.age = age
  }
}

Upvotes: 0

Views: 1488

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074295

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.

Upvotes: 1

Related Questions