typescript 打字稿类示例
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了typescript 打字稿类示例相关的知识,希望对你有一定的参考价值。
/* tslint:disable:max-classes-per-file */
class MyClass {
private intercept: number;
private slope: number;
constructor({ slope = 2, intercept = 1 } = { slope: 2, intercept: 1 }) {
this.intercept = intercept;
this.slope = slope;
}
public setIntercept(intercept: number) {
this.intercept = intercept;
return this;
}
public setSlope(slope: number) {
this.slope = slope;
return this;
}
public y(x: number) {
return (x * this.slope) + this.intercept;
}
}
class ClassA extends MyClass {
public eat() {
console.log('Eat an apple');
}
}
class ClassB extends MyClass {
public drink() {
console.log('drink a beverage');
}
}
const myClassObjectA = new ClassA();
myClassObjectA.eat(); // Eat an apple
console.log(myClassObjectA.y(1)); // (1 * 2) + 1 = 3
console.log(myClassObjectA.y(2)); // (2 * 2) + 1 = 5
myClassObjectA.setIntercept(3).setSlope(4);
console.log(myClassObjectA.y(1)); // (1 * 4) + 3 = 7
console.log(myClassObjectA.y(2)); // (2 * 4) + 3 = 11
const myClassObjectB = new ClassB({ slope: 3, intercept: 2 });
myClassObjectB.drink(); // Drink a beverage
console.log(myClassObjectB.y(1)); // (1 * 3) + 2 = 5
console.log(myClassObjectB.y(2)); // (2 * 3) + 2 = 8
myClassObjectB.setIntercept(3).setSlope(4);
console.log(myClassObjectB.y(1)); // (1 * 4) + 3 = 7
console.log(myClassObjectB.y(2)); // (2 * 4) + 3 = 11
以上是关于typescript 打字稿类示例的主要内容,如果未能解决你的问题,请参考以下文章
typescript 打字稿类示例
基于打字稿类的组件中的Vuetify日历
用值实例化打字稿类实例(对象初始化)
在打字稿中创建自己的反应路线类
将打字稿类转换为对象
打字稿类嵌套json猫