So I am used to languages like Swift and Rust, where you can declare functions on a type or interface after the fact.
I.e. in Rust, I can declare a data type, and then add methods using an impl
declaration:
struct Rectangle {
width: f64,
height: f64
}
impl Rectangle {
fn area(&self) -> f64 {
self.width * self.height
}
}
And I can do similar in Swift with an extension:
struct Rectangle {
let width: Float
let height: Float
}
extension Rectangle {
func area() -> Float {
return self.width * self.height
}
}
Is there a similar tool available in typescript to add methods to a typescript interface or type?
CodePudding user response:
In theory its possible. There are many ways to do that. Class is one of them
interface IRectangle {
width: number;
height: number;
area: () => number;
}
class Rectangle implements IRectangle {
constructor(public readonly width: number, public readonly height: number) {}
area() {
return this.height * this.width;
}
}
const rectangle = new Rectangle(4, 4);
console.log(rectangle.area());
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
TypeScript interfaces don't include any runtime implementation code, but you can extend existing interfaces. Here's an example:
interface Rectangle {
height: number;
width: number;
}
interface Rectangle {
area: () => number;
}
const r: Rectangle = {
height: 3,
width: 2,
area () {
return this.height * this.width;
},
};
console.log(r.area()); // 6
CodePudding user response:
You can it on class. Create class with constructor that implements the interface. And inside class find out the area with area
method. This way you dont have to create area method every time.
See the code below:
interface Rectangle {
height: number;
width: number;
}
class ChildRectangle implements Rectangle{
height: number;
width: number;
area(){
return this.width * this.height;
}
constructor(height: number, width: number) {
this.height = height;
this.width = width;
}
}
let childRectangle = new ChildRectangle(5,3);
console.log(childRectangle.area());
You can play here.