假设我有一个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

推荐答案

覆盖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));

会在吧台上运行toString,而不是Foo.

Typescript相关问答推荐

对可变位置的父对象的TypScript空判断

发出与HTML多姆事件重叠的Angular事件

如何为ViewContainerRef加载的Angular组件实现CanDeactivate保护?

为什么typescript要把这个空合并转换成三元?

如何在第一次加载组件时加载ref数组

从typescript中的对象数组中获取对象的值作为类型'

如果请求是流,如何等待所有响应块(Axios)

contextPaneTitleText类型的参数不能分配给remoteconfig类型的关键参数'""'''

不推荐使用Marker类-Google map API警告

如何按不能保证的功能过滤按键?

在TypeScrip的数组中判断模式类型

如何在编译时为不带常量的参数引发错误

具有自引用属性的接口

如何在方法中正确地传递来自TypeScrip对象的字段子集?

使用TypeScrip的类型继承

React router 6(数据路由)使用数据重定向

Angular NG8001错误.组件只能在一个页面上工作,而不是在她的页面上工作

在Google授权后由客户端接收令牌

TypeScrip:从嵌套的对象值创建新类型

Typescript泛型调用对象';s方法