gpt4 book ai didi

typescript - "This"在 TypeScript 中用作返回类型?

转载 作者:搜寻专家 更新时间:2023-10-30 20:40:03 25 4
gpt4 key购买 nike

我正在测试方法链,发现它可以使用“this”作为返回类型来完成?

这是一个例子:

class Shape {
color: String;

setColor(value: string): this { //Shape won't chain
this.color = value;
return this;
}
}

class Square extends Shape {
width: number;

setWidth(value: number): Square {
this.width = value;
return this;
}
}

function drawSquare(square: Square) {
alert("width: " + square.width + "\ncolor: " + square.color);
}

let rect = new Square().setWidth(20).setColor("blue");
drawSquare(rect);

Example in playground

这是混合基类和继承类时实现方法链接的正确方法吗?

最佳答案

当然,使用多态的 this 使得流畅的 api 非常容易表达为任何子类型“流”与 this 类型。检查Advanced Types节和 F 有界多态性

关于typescript - "This"在 TypeScript 中用作返回类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37400501/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com