TypeScript重写ToString()

时间:2016-02-12 11:28:56

标签: javascript typescript override tostring

我们说我有一个类Person,如下所示:

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

是否可以覆盖此类中的toString()方法,因此我可以执行以下操作?

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

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

此覆盖可能如下所示:

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

编辑:这实际上有效。有关详细信息,请参阅下面的答案。

2 个答案:

答案 0 :(得分:31)

覆盖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 wxpected; 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上运行。

答案 1 :(得分:6)

正如@Kruga所指出的那样,这个例子实际上似乎在运行时JavaScript中起作用。唯一的问题是TypeScript shows a type error

  

TS2345:类型'人物'不能分配给' string'。

类型的参数

要解决此消息,您必须:

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