1. 声明接口:
interface Person {
firstName: string;
lastName: string;
age: number;
}
let person: Person = {
firstName: "John",
lastName: "Doe",
age: 30
};
2. 可选属性:
interface Person {
firstName: string;
lastName?: string; // 可选属性
age: number;
}
let person: Person = {
firstName: "John",
age: 30
};
3. 只读属性:
interface Point {
readonly x: number;
readonly y: number;
}
let point: Point = { x: 10, y: 20 };
// point.x = 30; // 错误,只读属性不可修改
4. 函数类型:
interface MathFunction {
(x: number, y: number): number;
}
let add: MathFunction = function(x, y) {
return x + y;
};
5. 接口描述函数:
interface GreetFunction {
(name: string): string;
}
let greet: GreetFunction = function(name) {
return `Hello, ${name}!`;
};
6. 接口继承:
interface Shape {
color: string;
}
interface Circle extends Shape {
radius: number;
}
let myCircle: Circle = {
color: "red",
radius: 10
};
7. 类实现接口:
interface Animal {
makeSound(): void;
}
class Dog implements Animal {
makeSound() {
console.log("Woof!");
}
}
class Cat implements Animal {
makeSound() {
console.log("Meow!");
}
}
8. 接口作为类型:
interface Point {
x: number;
y: number;
}
let point: Point = { x: 10, y: 20 };
这些是 TypeScript 中关于接口的一些基本用法。接口是一种强大的工具,用于在编写代码时规定对象的形状和行为。通过接口,你可以提高代码的可读性和可维护性。
转载请注明出处:http://www.zyzy.cn/article/detail/13021/TypeScript