ts 中 interface
时间: 2025-06-16 14:26:53 浏览: 4
### TypeScript 中 `interface` 的用法与定义
TypeScript 的 `interface` 是一种类型定义工具,用于描述对象的结构、函数的参数和返回值等。它不仅可以提升代码的可读性和可维护性,还能为开发者提供更强大的类型检查功能[^2]。
#### 1. 基本定义
`interface` 的基本定义是通过键值对的形式来描述一个对象的结构。例如:
```typescript
interface User {
id: number;
name: string;
}
```
上述代码定义了一个 `User` 接口,表示该对象必须包含 `id` 和 `name` 两个属性,且它们的类型分别为 `number` 和 `string`。
#### 2. 可选属性
在某些情况下,对象的某些属性可能是可选的。可以通过在属性名后添加 `?` 来实现:
```typescript
interface User {
id: number;
name: string;
age?: number; // 可选属性
}
```
这样定义后,`age` 属性可以存在也可以不存在[^2]。
#### 3. 只读属性
如果希望某些属性在初始化后不能被修改,可以使用 `readonly` 关键字:
```typescript
interface User {
readonly id: number;
name: string;
}
```
在这种情况下,`id` 属性一旦被赋值就不能再更改[^4]。
#### 4. 函数类型
`interface` 还可以用来定义函数的类型,包括参数和返回值:
```typescript
interface SearchFunc {
(source: string, subString: string): boolean;
}
const searchString: SearchFunc = (source, subString) => {
return source.includes(subString);
};
```
这里定义了一个 `SearchFunc` 接口,表示这是一个接受两个字符串参数并返回布尔值的函数。
#### 5. 索引签名
当需要定义一个对象的动态键值对时,可以使用索引签名:
```typescript
interface StringArray {
[index: number]: string;
}
const arr: StringArray = ["a", "b", "c"];
console.log(arr[0]); // 输出 "a"
```
这段代码定义了一个只能存储字符串的数组[^2]。
#### 6. 继承
`interface` 支持继承其他接口,从而实现复用和扩展:
```typescript
interface Point {
x: number;
y: number;
}
interface Coordinate extends Point {
z: number;
}
```
上述代码中,`Coordinate` 继承了 `Point`,并额外添加了一个 `z` 属性[^3]。
#### 7. 映射类型
映射类型允许基于现有类型生成新的类型。例如,将所有属性变为只读:
```typescript
type ReadonlyCache<T> = { readonly [P in keyof T]: T[P]; };
```
这里定义了一个泛型接口 `ReadonlyCache`,它会将传入类型的每个属性都设置为只读[^4]。
---
### 示例代码
以下是一个综合示例,展示如何在 Vue 3 中结合 TypeScript 使用 `interface`:
```typescript
import { defineComponent, PropType } from 'vue';
interface User {
id: number;
name: string;
}
export default defineComponent({
name: 'UserProfile',
props: {
user: {
type: Object as PropType<User>,
required: true,
},
},
setup(props) {
console.log(props.user.name); // TypeScript 知道 props.user 的类型是 User
return {};
},
});
```
---
阅读全文
相关推荐

















