TypeScript 语法
参考:TypeScript
interface 接口
<template>
<div>
<p>{{ fullName }}</p>
</div>
</template>
<script lang="ts" setup>
import { ref } from 'vue';
interface Person {
firstName: string;
lastName: string;
}
function greeter(person: Person) {
return 'Hello, ' + person.firstName + ' ' + person.lastName;
}
let user = { firstName: '张', lastName: '三丰' };
const fullName =ref(greeter(user));
</script>
<style lang="scss" scoped></style>
在TypeScript中,如果两个类型其内部结构兼容,那么这两种类型兼容。这使我们实现一个接口,仅仅只需必要的结构形状,而不必有明确的implements子句。
Class 类
TypeScript支持新的JavaScript特性,像基于类的面向对象编程的支持。
创建一个具有构造函数和一些公共字段的Student类。注意:类和接口的良好配合使用,决定一个程序员的抽象水平。
此外,在构造函数参数中使用public是一种简写形式,它将自动创建具有该名称的属性。
<template>
<div>
{{ result }}
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
class Student {
fullName: string;
constructor(public firstName, public middleInitial, public lastName) {
this.fullName = firstName + ' ' + middleInitial + ' ' + lastName;
}
}
interface Person {
firstName: string;
lastName: string;
}
function greeter(person: Person) {
return 'Hello, ' + person.firstName + ' ' + person.lastName;
}
let user = new Student('李', '小', '红');
const result = ref(greeter(user));
</script>
<style lang="scss" scoped></style>
类型断言
类型断言好比其它语言里的类型转换,但是不进行特殊的数据检查和解构。 它没有运行时的影响,只是在编译阶段起作用。 TypeScript会假设你,程序员,已经进行了必须的检查。
let someValue: any = "this is a string"; let strLength: number = (someValue as string).length;
enum 枚举
默认情况下,从0开始为元素编号。
获取枚举的名称
enum Color {Red = 1, Green, Blue};
let colorName: string = Color[2];
遍历枚举
<template>
<el-select v-model="value" class="m-2" placeholder="Select" size="large">
<el-option
v-for="n in Object.keys(Color).length / 2"
:key="n - 1"
:label="Color[n - 1]"
:value="Color[n - 1]"
/>
</el-select>
</template>
<script setup lang="ts">
import { onMounted, ref, reactive, watch } from 'vue';
enum Color {
Red,
Green,
Blue,
}
const value = ref(Color[1]); //值为枚举的名称
let c: Color = Color.Red;
let colorName: string = Color[1]; //根据枚举值获取名称
onMounted(() => {
console.log(colorName);
});
watch(value, async (newValue) => {
console.log(value.value);
});
</script>
<style lang="scss" scoped></style>
浙公网安备 33010602011771号