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

时间:2024-03-28 22:23:34

接口

src/types/index.ts

//定义一个接口,用于限制person对象的具体属性
export interface PersonInter {
    id: string,
    name: string,
    age: number
}

src/components/person.vue

<template>
    <div class="person">
    </div>
</template>


<script lang="ts" setup name = "Person">

  import {type PersonInter} from '@/types' // 引入类型PersonInter前要加type

  let person:PersonInter = {
    id: 'wwesuperman',
    name: 'James',
    age: 35
  }

</script>


<style scoped>
  /* 可以添加样式 */
</style>

泛型

<template>
  <Person/>
</template>
  
<script setup lang="ts">
  import Person from './components/Person.vue'
  import {reactive} from 'vue'
  import {type Persons} from '@/types'

  let personList = reactive<Persons>([ //泛型
    {id:'No1', name:'Jack', age:11},
    {id:'No2', name:'Rose', age:12},
    {id:'No3', name:'Pete', age:13}
  ])

  console.log(personList)

</script>

<style scoped>
/* 可以添加一些样式 */
</style>

自定义类型

相关文章