记录 Vue3 + Ts 类型使用
阅读时长: 10 分钟
本文内容:记录在 Vue3 中使用 ts 时的各种写法.
类型大小写
vue3 + ts 项目中,类型一会儿大写一会儿小写。
怎么区分与基础类型使用? String、string、Number、number、Boolean、boolean …
-
在 js 中, 以
string 与 String
举例,后者是前者的包装对象,其他类型也一个意思。 -
在 ts 中,以
string 与 String
举例,前者是 ts 中的类型,后者是 js 中的对象,其他类型也一个意思。
结论:在 ts 中使用小写 定义参数类型(例如:定义 title: string,而不是 title: String )。
<script setup lang="ts">interface DialogOptions {title: string; // 小写visible?: boolean; // 小写}const props = defineProps<DialogOptions>();</script>
props 类型约束
对于 props 类型进行限制时有 4 种写法:
1.(推荐)
先定义接口,然后使用
缺陷: 无法定义默认值
<script setup lang="ts">interface DialogOptions {title: string;visible?: boolean;callback: (row: any) => any;}const props = defineProps<DialogOptions>();
</script>
2.(不推荐)
直接通过泛型约束类型
缺陷:写起来过于复杂
<script setup lang="ts">const props = defineProps<{title: string;visible?: boolean;callback: (row: any) => any;}>();
</script>
3.(推荐)
先定义接口,结合 Vue3 框架提供的 withDefaults()
来约束类型
适用于:可定义默认值
<script setup lang="ts">interface DialogOptions {title?: string;visible?: boolean;callback: (row: any) => any;}const props = withDefaults(defineProps<DialogOptions>(), {title: "dialog title",visible: false,});
</script>
4.(不推荐)
保持与 vue2 一致的写法。使用 Vue3 框架提供的宏函数 defineProps()
内置的类型推导功能
优点:此写法虽然与 Vue2 中写法一致,但是 type 的值必须使用大写。大小写混用,容易造成认知错误
<script setup lang="ts">const props = defineProps({title: {type: String, // 大写default: "Dialog",required: true,},visible: {type: Boolean, // 大写default: false,required: false,},callback: {type: Function, // 大写default: () => {},required: false,},});
</script>
4.(......)
使用 validor 验证 props 参数的情况
需要用到
validator
来约束值时,使用此方法,无法分离使用(如果你有好办法,请评论留言)
<script setup lang="ts">const props = defineProps({title: {type: String as PropType<"提示" | "弹窗" | "确认框">,default: "提示",validator: (prop: string) => ["提示", "弹窗", "确认框"].includes(prop),},visible: {type: Boolean,default: false,required: false,},callback: {type: Function,default: () => {},required: false,},});
</script>
emit 类型约束
- 数组用法(无法约束类型)
<script setup lang="ts">// 申明const emit = defineEmits(["receiveData"]);// 使用const clickButton = () => {emit("receiveData", "456");};
</script>
- Object 用法 (无法约束类型)
<script setup lang="ts">const emit = defineEmits({receiveData: (payload) => {return typeof payload === "string";},});// 使用const clickButton = () => {emit("receiveData", 123456);};
</script>
ref 类型约束
- 通过泛型约束
<script setup lang="ts">interface ReceiveData {value: number;}const year = ref<ReceiveData>({ value: 2023 });console.log(year.value);
</script>
- 通过值约束
<script setup lang="ts">interface ReceiveData {value: number;}const year: Ref<ReceiveData> = ref({ value: 2023 });console.log(year.value);
</script>
reactive 类型约束
<script setup lang="ts">interface ReceiveData {value: number;}// 1. 通过泛型约束const year = reactive<ReceiveData>({ value: 2023 });console.log(year);// 2. 通过值约束const year: ReceiveData = reactive({ value: 2023 });console.log(year);
</script>
参考阅读
- types validator issuse#8152