typescript-类实例的默认值

问题描述 投票:0回答:1

我想知道打字稿中是否存在此功能:

如果我上过课

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

并且我希望它在调用实例时返回一些默认值

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

如果在不访问实例属性或方法的情况下调用实例,如何实现返回自定义/默认值?有没有可以使属性以这种方式起作用的关键字?我可能会想到一个“默认”关键字,但是有类似的东西吗?

class Person {
  default name: string
  age: number
  constructor(name, age){
    this.name = name
    this.age = age
  }
}
typescript syntax
1个回答
1
投票

最接近的是重写从toString继承的valueOf和/或Object.prototype方法。 但是console.log在大多​​数实现中都不使用那些,您必须执行console.log(String(person))或类似的操作。

例如,toString

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

实时示例(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));

类似地,如果您覆盖valueOf并返回数字,则当实例使用数字运算符时,它将使用数字valueOf返回:

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可以返回任何内容(包括字符串),尽管如果它返回非原始类型,则该对象将以该对象的通常方式转换为原始类型。


附带说明:您可以使用TypeScript的自动属性声明为自己节省一些输入:

class Person {
  constructor(public name: string, public age: number) {
  }
  toString(): string {
    return this.name;
  }
}

构造函数的参数列表中的public告诉TypeScript将它们创建为公共属性,并在构造函数的代码中为您分配它们。

© www.soinside.com 2019 - 2024. All rights reserved.