【问题标题】:TypeScript override ToString() [closed]TypeScript 覆盖 ToString() [关闭]
【发布时间】:2016-05-23 12:52:46
【问题描述】:

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

【问题讨论】:

标签: javascript typescript overriding tostring


【解决方案1】:

覆盖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 属性(或任何属性)
  • 我更新了我的答案。您的问题可能是定义 toString 之类的函数。将其定义为 lambda 属性可能会更好(就像我在新的更详尽的示例中所做的那样。)
  • 工作就像一个魅力,谢谢!
  • @Nypan 是否有使用 public toString = () : string => { 而不是 public toString(): string { 的专业论点?
  • 是的,使用 t() : => 可确保 this 将是您在 toString 覆盖中所期望的。您可以阅读arrow functions 以了解更多信息。但这里的基本区别是箭头函数不绑定自己的 this。
【解决方案2】:

正如@Kruga 所指出的,该示例实际上似乎在运行时 JavaScript 中工作。唯一的问题是TypeScript shows a type error

TS2345:“Person”类型的参数不能分配给“string”类型的参数。

要解决此消息,您必须:

  • 明确致电.toString()
  • 或将对象与字符串连接(例如`${obj}`obj + ''
  • 或者使用obj as any(不推荐,因为你会失去类型安全)

【讨论】:

  • “用空字符串连接对象”对我有用
  • 在这种情况下,与空字符串的更“hacky”连接相比,对我来说显式调用toString() 似乎是最佳实践。
猜你喜欢
  • 2020-03-09
  • 2016-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-27
  • 2010-11-23
相关资源
最近更新 更多