ts接口介绍

在typescript里,接口的作用是代码的一种约定和规范

一、对象型接口:对对象的约束

interface myInfo{
    name:string;
    age:number
}
function printName({name,age}:myInfo){
    console.log(name);
    console.log(age);
    return myInfo;
}

也可以使返回值为两个值

二、函数类型接口:对函数的约束

基础语法:

interface 接口名 {
    (参数名1: 参数值1, 参数名2: 参数值2): 返回值类型
}

例两个数相加

interface addNum={
    (a:number,b:number):number
}
const add: addNum = (a, b) => {
    return a + b;
}
add(1, 2)

三、可索引类型的接口:对数组的约束

例:

interface StringArray:{
    [index:number]:string
}

let myArray: StringArray;
myArray = ["zhang", "ben"];

let myStr: string = myArray[0];//用number索引数组得到字符串的返回值

四、泛型接口

//定义一个泛型接口
interface NameInterface<T>{
    getName:(name:string) => T
}

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在 Vue 3 中使用 TypeScript 进行接口请求,你可以按照以下步骤进行操作: 1. 安装依赖:首先,你需要安装 Axios 库来进行接口请求。在项目根目录下运行以下命令: ```bash npm install axios ``` 2. 创建接口定义:在你的 TypeScript 文件中创建一个接口定义返回数据的结构。例如,创建一个 `User` 接口定义用户信息: ```typescript interface User { id: number; name: string; email: string; } ``` 3. 创建服务文件:创建一个服务文件来封装接口请求逻辑。在该文件中,你可以使用 Axios 来发送 HTTP 请求,并使用 TypeScript 的泛型来指定响应的数据类型。例如,创建一个 `UserService` 文件: ```typescript import axios, { AxiosResponse } from 'axios'; const API_BASE_URL = 'https://api.example.com'; export async function getUserById(id: number): Promise<User> { const response: AxiosResponse<User> = await axios.get(`${API_BASE_URL}/users/${id}`); return response.data; } ``` 4. 在组件中使用服务:在你的 Vue 组件中导入并使用服务来进行接口请求。例如,在一个 `UserComponent` 组件中使用 `UserService` 的 `getUserById` 方法: ```typescript <script lang="ts"> import { defineComponent, ref } from 'vue'; import { getUserById } from './services/UserService'; export default defineComponent({ name: 'UserComponent', setup() { const user = ref<User | null>(null); const fetchUser = async (id: number) => { user.value = await getUserById(id); }; // 使用 fetchUser 方法来获取用户信息 fetchUser(1); return { user, }; }, }); </script> ``` 这样,你就可以在 Vue 3 中使用 TypeScript 进行接口请求了。记得根据你的项目需求进行相应的调整。希望能对你有所帮助!如果还有任何问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值