这里记录下typescript中接口、泛型和自定义类型的使用
接口定义
// 定义一个接口,用来限制Teacher的属性
export interface Teacher {
name: string;
age: number;
gender: string;
}
export type teacherList = Teacher[];
// 一个自定义类型
export type Teachers = Array<Teacher>;
使用
<script lang = "ts" setup name = "Teacher">
import { type Teacher, type Teachers } from "@/types"
let teacher : Teacher = {
name: "John",
age: 25,
gender: "Male"
}
//定义teacher类型数组
let teacherList : Teacher[] = [
{
name: "Alice",
age: 26,
gender: "Female"
},
{
name: "Bob",
age: 27,
gender: "Male"
}
]
// 使用泛型定义数组
let teachers : Array<Teacher> = [
{
name: "Alice",
age: 26,
gender: "Female"
},
{
name: "Bob",
age: 27,
gender: "Male"
}
]
let teacherArray : Teachers = [
{
name: "Alice",
age: 26,
gender: "Female"
},
{
name: "Bob",
age: 27,
gender: "Male"
}
]
</script>
<template>
<div>
<h1>Welcome, {{teacher.name}}!</h1>
<p>You are {{teacher.age}} years old and {{teacher.gender}}.</p>
</div>
</template>
<style scoped>
</style>