Ts的接口、泛型、自定义类型

一、概述

TypeScript(TS)是一种强类型的JavaScript超集,它为JavaScript代码提供了类型检查功能。在TypeScript中,接口(Interfaces)、泛型(Generics)和自定义类型(Custom Types)是定义和强化代码类型的三种重要方式。

二、接口(Interfaces)
接口是用来定义对象、类或函数的形状(shape)的一种类型系统。它描述了一组属性的集合,这些属性包括名称和类型。接口在TypeScript中是通过关键字interface来定义的。

简单接口:

interface Person {
  name: string;
  age: number;
}

函数接口:

interface ClickHandler {
  (event: MouseEvent): void;
}

接口的继承
接口可以继承另一个接口,使用extends关键字:

interface Shape {
  color: string;
}

interface Square extends Shape {
  sideLength: number;
}

三、泛型(Generics)
泛型是一种可以在定义函数、接口、类的时候,不预先指定具体的类型,而是在使用的时候再指定类型的特性。它允许你在不牺牲类型安全性的同时编写可重用的组件。

泛型函数:

function identity<T>(arg: T): T {
  return arg;
}

泛型类

class Box<T> {
  private content: T;
  constructor(content: T) {
    this.content = content;
  }
  getContent(): T {
    return this.content;
  }
}

泛型接口

interface ResponseData<T> {
  data: T;
  status: number;
}

四、自定义类型(Custom Types)
自定义类型通常是指那些使用TypeScript提供的类型系统来创建的新类型。这包括了使用type关键字定义的类型、联合类型、元组类型等。

使用type自定义接口类型

type Point = {
  x: number;
  y: number;
};

 联合类型:

type MaybeNumber = number | null;

元组类型

type Pair<T1, T2> = [T1, T2];

五、defineProps

 是 Vue 3 中引入的一个新的 API,用于在组件内部定义和验证 props。这个 API 使得组件的 props 定义更加清晰和可维护,并且提供了更好的类型检查支持。

App向组件person传递数据

App.vue:

<template><!--html-->
    <div class="app">
        <Person :list="personlist"/>
    </div>
</template>
<script lang="ts" setup name="App">//javascript
import Person from './components/Person.vue'
  import { reactive } from 'vue'
    import { type PersonInter,type Persons} from './types/index'
  let personlist=reactive<Persons>([
    {id:'0212', name:"张三",age:18 },
    {id:'0213', name:"李四",age:19 },
    {id:'0214', name:"王五",age:20 }
  ])
</script>

<style>/*css样式*/ 
     .app{
        background-color: #ddd;
        box-shadow: 0 0 10px;
        border-radius: 10px;
        padding: 20px;
     }
</style>

 Person.vue:

<!--vue简单框架-->
<template>
<div class="person">
    <ul v-for="p in list" :key="p.id">
        <li>
            {{ p.name }}--{{p.age  }}
        </li>
    </ul>
</div>
</template>

<script lang='ts'setup name="">
    import { DefineProps,withDefaults } from 'vue';
    import {PersonInter, Persons} from '../types/index'
    //只接收list
    defineProps(['list'])
    //接收list,并且限制类型
    defineProps<{list:Persons}>()
     //接收list+限制类型+限制必要性+限制默认值
     withDefaults(defineProps<{list?:Persons}>(),{
        list:()=>[{id:"23812",name:'康师傅',age:37}]
     })
</script>

<style scoped>
</style>

type文件夹下的index.ts

//定义一个接口,用来限制对象的属性
export interface PersonInter{
    id:string,
    name:string,
    age:number
}
//自定义类型
/* export type Persons=Array<PersonInter> */
export type Persons=PersonInter[]

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值