interface用法
时间: 2023-05-28 08:07:21 浏览: 100
interface是一种定义对象类型的语法结构,它可以定义对象的属性、方法以及函数类型。在JavaScript中,interface通常用于描述对象的形状,用于类型检查和静态分析。在TypeScript中,interface也可以用于定义类、函数等类型。
interface的基本用法如下:
1. 定义一个interface
```typescript
interface Person {
name: string;
age: number;
}
```
2. 使用interface
```typescript
function printPerson(person: Person) {
console.log(`Name: ${person.name}, Age: ${person.age}`);
}
const person = { name: 'Tom', age: 20 };
printPerson(person);
```
3. 可选属性
```typescript
interface Person {
name: string;
age?: number;
}
const person1 = { name: 'Tom' };
const person2 = { name: 'Tom', age: 20 };
```
4. 只读属性
```typescript
interface Person {
readonly name: string;
age: number;
}
const person = { name: 'Tom', age: 20 };
person.name = 'Jerry'; // Error: Cannot assign to 'name' because it is a read-only property.
```
5. 函数类型
```typescript
interface Add {
(a: number, b: number): number;
}
const add: Add = (a, b) => a + b;
```
6. 继承接口
```typescript
interface Person {
name: string;
age: number;
}
interface Student extends Person {
grade: number;
}
const student = { name: 'Tom', age: 20, grade: 3 };
```
阅读全文