2016-02-12 72 views
22

比方說,我有一個類Person它看起來像這樣:打字稿覆蓋的ToString()

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; 
} 

編輯:這實際工作。詳情請見下面的答案。

+3

你試過自​​己的例子嗎?似乎已經工作了。 https://jsfiddle.net/sy8wttvw/ – Kruga

回答

16

重寫對字符串按預期工作種類:

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 concatinating strings 
console.log("" + a); // outputs: Foo (id: 23423) 
console.log(`${a}`); // outputs: Foo (id: 23423) 

// and for overridden to string 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("" + (<Foo>(new Bar()))); 

將在Bar上運行toString,而不是在Foo上運行。

+0

這有點適合我,但得到更具體。我有一個像這樣的'代碼'模塊的ts類Entidades {0}導出類eEpisodio {公共Id:numer}}'代碼' 如果我嘗試使用我的toString()方法添加一些屬性,它不起作用,它似乎沒有找到Id的財產(或任何) –

+1

我更新了我的答案。你可能遇到的問題是像函數一樣定義toString。將其定義爲lambda屬性可能會更好(如我在新的更詳盡的示例中所做的那樣)。 – Nypan

+0

像魅力一樣工作,謝謝! –

1

正如@Kruga指出的那樣,該示例似乎在運行時JavaScript中起作用。唯一的問題是,這是TypeScript shows a type error

TS2345:參數類型「人」的是不能分配給類型「字符串」的參數。

要解決此消息,則必須:

  • 呼叫.toString()明確
  • 或者用字符串拼接的對象(例如`${obj}`obj + ''
  • 或者使用obj as any(不建議作爲你會失去類型安全)
+1

「用空字符串連接對象」爲我工作 –