详细介绍一下 typeScript 接口以及使用示例
TypeScript 接口是一种用于描述对象形状的类型约束方式,它可以定义对象的属性、方法、可选属性、只读属性等,以便在编译期检查代码的正确性。
TypeScript 接口的定义方式如下:
interface InterfaceName {
property1: type;
property2?: type;
readonly property3: type;
method1(): returnType;
method2(param: type): returnType;
}
其中,InterfaceName 是接口的名称,property1、property2、property3 是接口的属性,method1、method2 是接口的方法,type 是属性的类型,returnType 是方法的返回值类型,param 是方法的参数类型。
下面是一个使用 TypeScript 接口的示例:
interface Person {
name: string;
age: number;
gender?: string;
readonly id: number;
sayHello(): void;
}
class Student implements Person {
name: string;
age: number;
id: number;
constructor(name: string, age: number, id: number) {
this.name = name;
this.age = age;
this.id = id;
}
sayHello() {
console.log(`Hello, my name is ${this.name}.`);
}
}
const student = new Student("Tom", 18, 10001);
student.sayHello(); // 输出:Hello, my name is Tom.
在上面的示例中,定义了一个 Person 接口,它有 name、age、gender、id 和 sayHello 属性及方法。然后定义了一个 Student 类,它实现了 Person 接口,并且实例化了一个 Student 对象,调用 sayHello 方法输出信息。
总而言之,TypeScript 接口提供了一种简洁、清晰的方式来定义对象的形状和类型,使得代码更加可读、可维护和可扩展。
原文地址: https://www.cveoy.top/t/topic/bEAe 著作权归作者所有。请勿转载和采集!