当前位置:网站首页>【TS】Class
【TS】Class
2022-07-19 18:50:00 【Superman_H】
类
npm i typescript -g
- 创建、配置 tsconfig.json
{
"compilerOptions": {
"module": "es2015",
"target": "es2015",
"strict": true,
"outDir": "./dist"
},
"include": ["./src/**/*"]
}
- 创建类
class Person {
name: string = "superman"; // 定义实例属性,`: string` 可以不写,因为初始化时能自动识别类型
static age: number = 21; // 定义类属性 ( 静态属性 )
readonly gender: string = "male"; // 定义只读实例属性
static readonly kind: string = "best"; // 定义只读类属性 ( static 和 readonly 的位置不能调换 )
// 定义实例方法
sayName() {
console.log("使用实例方法", this); // this 指向当前实例
}
// 定义类方法
static sayHello() {
console.log("使用类方法", this); // this 指向当前类
}
}
const per = new Person();
console.log("访问实例属性", per.name);
console.log("访问类属性", Person.age);
per.sayName();
Person.sayHello();
tsc -w
构造函数
- 构造函数会在创建实例对象
new Xxx()
时执行 - 构造函数的
this
指向当前实例
class Person {
// 在类中 定义属性
name: string;
age: number;
// 构造函数
constructor(name: string = "小明", age: number = 21) {
// 在构造函数中 初始化属性
this.name = name;
this.age = age;
}
}
const per1 = new Person();
const per2 = new Person("小王", 22);
console.log("per1", per1);
console.log("per2", per2);
继承
class Person {
name: string;
constructor(name: string = "小明") {
this.name = name;
}
sayHello() {
console.log("person");
}
}
// 继承后,子类会拥有父类所有的方法和属性
class Student extends Person {
// 子类中写的方法是子类自己的方法
// 如果子类中写的方法和父类中的方法同名,会覆盖父类中的方法(方法重写)
sayHello() {
console.log("student");
}
}
const per = new Person();
const stu = new Student("小王");
console.log("per", per);
console.log("stu", stu);
per.sayHello(); // person
stu.sayHello(); // student
super 关键字
class Person {
name: string;
constructor(name: string = "小明") {
this.name = name;
}
sayHello() {
console.log("person");
}
}
class Student extends Person {
age: number;
constructor(name: string = "大明", age: number = 21) {
super(name); // 调用父类的 constructor 函数
this.age = age;
}
sayHello(): void {
super.sayHello(); // 调用父类的 sayHello 函数
console.log("student");
}
}
const per = new Person();
const stu = new Student();
console.log("per", per); // per Person {name: '小明'}
console.log("stu", stu); // stu Student {name: '大明', age: 21}
per.sayHello(); // person
stu.sayHello(); // person student
抽象类
// 抽象类:仅供继承使用,不能用于创建实例
abstract class Person {
name: string;
constructor(name: string = "superman") {
this.name = name;
}
// 抽象方法:仅供重写使用,需声明返回值的类型
// 子类中必须重写 [抽象方法]
abstract sayHello(): void;
}
class Student extends Person {
age: number;
constructor(name: string = "superStudent", age: number = 21) {
super(name);
this.age = age;
}
sayHello() {
console.log("student");
}
}
const stu = new Student();
console.log("stu", stu);
stu.sayHello();
接口
- 接口:可以当成类型声明去使用
interface myInterface {
name: string; age: number; }
const obj: myInterface = {
name: "superman", age: 21 };
console.log("obj", obj); // obj {name: 'superman', age: 21}
我们来对比一下 [类型别名]
type myType = {
name: string; age: number };
const obj: myType = {
name: "superman", age: 21 };
console.log("obj", obj); // obj {name: 'superman', age: 21}
- 类型别名不能重复定义;接口可以重复定义
interface myInterface {
name: string;
age: number;
}
interface myInterface {
gender: string;
}
此时等同于:
interface myInterface {
name: string;
age: number;
gender: string;
}
- 接口:用于定义类结构,即限制类的结构
// 接口中 所有的属性都不能有实际的值
// 所有的方法都是抽象方法
interface myInterface {
name: string;
sayHello(): void;
}
// 使用类继承接口
class MyClass implements myInterface {
constructor(name: string) {
super(name);
}
sayHello(): void {
console.log("MyClass");
}
}
const myClass = new MyClass("superman");
console.log("myClass", myClass); // myClass MyClass {name: 'superman'}
属性的封装
public
- 公共属性,可以在任何地方访问(修改)(默认)protect
- 受保护的属性,可以在当前类及其子类中访问(修改)private
- 私有属性,只可以在当前类中访问(修改)
class Person {
// public 属性
name: string;
// private 属性 - 我们约定 private 属性以 $_ 开头
private $_age: number;
constructor(name: string = "superman", age: number = 21) {
this.name = name;
this.$_age = age;
}
}
const per = new Person();
console.log("name", per.name);
// console.log("age", per.$_age); 直接飘红
- 在类的外部,想要访问私有属性,可以设置专门的方法获取
class Person {
private $_age: number;
constructor(age: number = 21) {
this.$_age = age;
}
// 访问私有属性 age
getAge(): number {
return this.$_age;
}
// 设置私有属性 age
setAge(age: number): void {
this.$_age = age > 0 ? age : 0;
}
}
const per = new Person();
console.log("age", per.getAge());
per.setAge(31);
console.log("age", per.getAge());
- TS 中可以使用 getter & setter
class Person {
private $_age: number;
constructor(age: number = 21) {
this.$_age = age;
}
// getter
get age(): number {
return this.$_age;
}
// setter - 不能设置返回值类型
set age(age: number) {
this.$_age = age > 0 ? age : 0;
}
}
const per = new Person();
console.log("age", per.age); // 访问 per.age 时会调用 getter
per.age = 31; // 修改 per.age 时会调用 setter
console.log("age", per.age);
- 定义类的简写:
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
上例的语法糖写法:
class Person {
constructor(public name: string, public age: number) {
}
}
泛型
在定义函数或类时,如果类型不明确,可以使用泛型
// 定义使用泛型的函数
function fun<T>(val: T): T {
return val;
}
// 调用使用泛型的函数
fun(1); // 直接调用 不指定泛型,TS 会自动判断类型
fun<string>("superman"); // 指定泛型
// 定义使用泛型的类
class Person<T> {
constructor(public name: T) {
}
}
// 调用使用泛型的类
const per1 = new Person("superman"); // 直接调用 不指定泛型,TS 会自动识别
const per2 = new Person<string>("superwoman"); // 指定泛型
泛型可以同时指定多个
function fun<T, K>(val1: T, val2: K): T {
console.log("val1", val1);
console.log("val2", val2);
return val1;
}
fun<string, number>("superman", 21);
约束泛型的类型:
interface Inter {
length: number;
}
// T extends Inter 表示泛型 T 必须是 Inter 的实现类(子类)
function fun<T extends Inter>(val1: T): T {
return val1;
}
// 必须是含有 length 属性的对象
fun({
length: 18 });
fun([1]);
fun("superman");
边栏推荐
- Minitouch click principle
- Permissionerror: [winerror 5] access denied
- STL 笔记(四):字符串
- 《安富莱嵌入式周报》第274期:2022.07.11--2022.07.17
- Distribution and application of Internet of things technology in the industrial pattern of Internet of things
- GEE(7):GEE插件Open Earth Engine extension提高效率
- Install OpenCL support for halide
- Anfulai embedded weekly report no. 274: 2022.07.11--2022.07.17
- STL 笔记(六):容器——vector
- JS whether a certain time is within a certain time range
猜你喜欢
物联网技术在物联网产业格局的分布与应用
6. Look for duplicates
After 10 years of summary and sharing with test engineers, an article will teach you how to quickly find bugs and write test cases
现在运营想要查看所有来自浙江大学的用户题目回答明细情况,请你取出相应数据
"Viewpager" and banner in compose
Soft test director: "after five years of work, you don't even know about the server interface test“
[Network Communication II] TCP reference model
4、图网络分类
STL 笔记(一):知识体系
软测总监:“ 工作五年你连服务端接口测试还不知道?“
随机推荐
现在运营想要查看所有来自浙江大学的用户题目回答明细情况,请你取出相应数据
STM32F1与STM32CubeIDE编程实例-HMC5883电子罗盘驱动
Programming examples of stm32f1 and stm32subeide -bmp280 pneumatic temperature sensor drive
STL 笔记(一):知识体系
TZC 1283: simple sort - Hill sort
[liunx] wait function and waitpid function
剑指 Offer II 014. 字符串中的变位词
力扣第三题——无重复字符的最长子串
力扣 731. 我的日程安排表 II
SQL Server数据库备份和恢复措施
软件测试岗位就业竞争压力大,985毕业的“打工人“同样存在苦不堪言。
Get the ID of the record just added
Inftnews | the future of music in Web3
事件循环机制 浏览器-nodejs-async/await执行顺序-promise执行顺序面试题
技术面的最后一个问题难住我:如何规避生产环境性能测试风险 ?
Uzbek President zelenski dismissed deputy director of the National Security Agency
Directeur des tests Soft: « après cinq ans de travail, vous ne savez même pas comment tester l'interface serveur? »
【Liunx】wait函数 和 waitpid函数
STM32开发笔记121:我理解的卡尔曼滤波
微信小程序中image组件用作背景图片时