我想知道打字稿中是否存在此功能:
如果我上课
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
}
}
答案 0 :(得分:1)
最近的事情是重写从#!/bin/bash
subjectHash=`openssl x509 -inform PEM -subject_hash_old -in server.crt | head -n 1`
openssl x509 -in server.crt -inform PEM -outform DER -out $subjectHash.0
adb root
adb push ./$subjectHash.0 /data/misc/user/0/cacerts-added/$subjectHash.0
adb shell "su 0 chmod 644 /data/misc/user/0/cacerts-added/$subjectHash.0"
adb reboot
继承的toString
和/或valueOf
方法。 但是:Object.prototype
在大多数实现中都不使用它们,您必须做console.log
或类似的事情。
例如console.log(String(person))
:
toString
实时示例(JavaScript,TypeScript version on the playground):
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
toString(): string {
return this.name;
}
}
类似地,如果您覆盖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
可以返回任何内容(包括字符串),尽管如果它返回非原始类型,则该对象将以该对象的通常方式转换为原始类型。
旁注:您可以使用TypeScript的自动属性声明为自己节省一些输入:
valueOf
构造函数的参数列表中的class Person {
constructor(public name: string, public age: number) {
}
toString(): string {
return this.name;
}
}
告诉TypeScript将其创建为公共属性,并在构造函数的代码中为您分配它们。