Javascript 打字稿覆盖 ToString()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35361482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeScript override ToString()
提问by Duncan Luk
Let's say I have a class Person
which looks like this:
假设我有一个Person
看起来像这样的课程:
class Person {
constructor(
public firstName: string,
public lastName: string,
public age: number
) {}
}
Is it possible to override the toString()
method in this class, so I could do something like the following?
是否可以覆盖toString()
此类中的方法,以便我可以执行以下操作?
function alertMessage(message: string) {
alert(message);
}
alertMessage(new Person('John', 'Smith', 20));
This override could look something like this:
此覆盖可能如下所示:
public toString(): string {
return this.firstName + ' ' + this.lastName;
}
Edit: This actually works. See answers below for details.
编辑:这实际上有效。有关详细信息,请参阅下面的答案。
采纳答案by Nypan
Overriding toString
works kind of as expected:
覆盖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)
What can sometimes be an issue though is that it is not possible to access the toString
of a parent class:
有时可能会出现问题的是,无法访问toString
父类的 :
console.log("" + (new Bar() as Foo));
Will run the toString on Bar, not on Foo.
将在 Bar 上运行 toString,而不是在 Foo 上。
回答by Duncan Luk
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.
正如@Kruga 指出的那样,该示例实际上似乎可以在运行时 JavaScript 中运行。唯一的问题是TypeScript 显示类型错误。
TS2345:Argument of type 'Person' is not assignable to parameter of type 'string'.
TS2345:“Person”类型的参数不能分配给“string”类型的参数。
To resolve this message, you must either:
要解决此消息,您必须:
- Call
.toString()
explicitly - Or concatenate the object with a string (e.g.
`${obj}`
orobj + ''
) - Or use
obj as any
(not recommended as you will lose type safety)
.toString()
显式调用- 或用字符串连接对象(例如
`${obj}`
或obj + ''
) - 或者使用
obj as any
(不推荐,因为你会失去类型安全)