TypeScript 覆盖 ToString()

假设我有一个类 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”的参数。

如何为这个 string参数指定一个 Person

83731 次浏览

Overriding toString works kind of as expected:

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)

What can sometimes be an issue though is that it is not possible to access the toString of a parent class:

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

Will run the toString on Bar, not on Foo.

As pointed out by @Kruga, the example actually seemed to work in runtime JavaScript. The only problem with this is that TypeScript shows a type error.

TS2345: Argument of type 'Person' is not assignable to parameter of type 'string'.

To resolve this message, you must either:

  • Call .toString() explicitly
  • Or concatenate the object with a string (e.g. `${obj}` or obj + '')
  • Or use obj as any (not recommended as you will lose type safety)