TypeScript重写ToString()

92

假设我有一个名为Person的类,它看起来像这样:

class Person {
    constructor(
        public firstName: string,
        public lastName: string,
        public age: number
    ) {}
}

我已经重写了toString方法,代码如下。

public toString(): string {
    return this.firstName + ' ' + this.lastName;
}

现在我希望能够做到以下事情,这在运行时可以实现:

function alertMessage(message: string) {
    alert(message);
}

alertMessage(new Person('John', 'Smith', 20));

但是这仍然给我带来了这个错误:

TS2345:类型 'Person' 的参数不能赋值给类型 'string' 的参数。

我该如何将一个 Person 分配给这个 string 参数?


8
你有尝试过自己的示例吗?似乎已经起作用了。https://jsfiddle.net/sy8wttvw/ - Kruga
2个回答

84

覆盖toString的效果与预期有些类似:

class Foo {
    private id: number = 23423;
    public toString = () : string => {
        return `Foo (id: ${this.id})`;
    }
}

class Bar extends Foo {
   private name:string = "Some name"; 
   public toString = () : string => {
        return `Bar (${this.name})`;
    }
}

let a: Foo = new Foo();
// Calling log like this will not automatically invoke toString
console.log(a); // outputs: Foo { id: 23423, toString: [Function] }

// To string will be called when concatenating strings
console.log("" + a); // outputs: Foo (id: 23423)
console.log(`${a}`); // outputs: Foo (id: 23423)

// and for overridden toString in subclass..
let b: Bar = new Bar();
console.log(b); // outputs: Bar { id: 23423, toString: [Function], name: 'Some name' }
console.log("" + b); // outputs: Bar (Some name)
console.log(`${b}`); // outputs: Bar (Some name)

// This also works as expected; toString is run on Bar instance. 
let c: Foo = new Bar();
console.log(c); // outputs: Bar { id: 23423, toString: [Function], name: 'Some name' }
console.log("" + c); // outputs: Bar (Some name)
console.log(`${c}`); // outputs: Bar (Some name)

但有时问题在于无法访问父类的toString方法:

console.log("" + (new Bar() as Foo));

将在Bar上运行toString,而不是Foo。


这对我有点用,但需要更具体一些。我有一个像这样的ts类 code module Entidades { export class eEpisodio{ public Id: numer} }code 如果我尝试使用我的toString()方法添加一些属性,它不起作用,似乎找不到Id属性(或任何属性)。 - Mario Garcia
1
我更新了我的答案。你可能的问题是将toString定义为函数。将其定义为lambda属性可能会更好(就像我在我的新的更详尽的示例中所做的那样)。 - Nypan
1
@Nypan 这里有使用 public toString = () : string => { 替代 public toString(): string { 的有力论据吗? - illnr
2
是的,使用t() : =>确保在toString重写中this是您期望的。您可以阅读有关箭头函数的内容以了解更多信息。但这里的基本区别是箭头函数不会绑定它们自己的this。 - Nypan

15
好的,请提供需要翻译的内容。

正如@Kruga所指出的,在运行JavaScript时,该示例似乎实际上可以工作。唯一的问题是


1
"将对象与空字符串连接" 对我有效。 - Dan Loughney
6
在这种情况下,与使用空字符串进行“hacky”连接相比,显式调用toString()似乎更符合最佳实践。 - Arnold Schrijver

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接