参数和返回值
function calculateGrade(course1: number, course2: number) : string {
return (course1 + course2) > 70 ? 'A' : 'B';
}
interface User {
name: string;
id: number;
}
const user: User = {}
指定多个类型
function getLength(obj: string | string[]) {
return obj.length;
}
type Predicate string typeof s === "string" number typeof n === "number" boolean typeof b === "boolean" undefined typeof undefined === "undefined" function typeof f === "function" array Array.isArray(a)
- Type-Safe Props
Generic type argument:
// generic not support required attribute
const props = defineProps<{
limit: number,
alertMessageOnLimit: string
}>()
extract generic type to interface
interface Props {
limit: number
alertMessageOnLimit?: string
}
const props = defineProps<Props>()
Function argument:
const props = defineProps({
limit: { type: Number, required: true },
alertMessageOnLimit: { type: String, required: true }
})
- Type-Safe Emit
<script setup lang="ts">
// 运行时
const emit = defineEmits(['change', 'update'])
// 基于类型
const emit = defineEmits<{
(event: 'change', id: number): void
(event: 'update', value: string): void
}>()
const emit = defineEmits<{
(event: 'add-count', num: number): void
(event: 'reset-count'): void
}>()