如何使用TypeScript防止Vue 3中嵌套prop字段的变化?

bogh5gae  于 2023-05-30  发布在  TypeScript
关注(0)|答案(1)|浏览(118)

假设我有以下SFC组件:

<script setup lang="ts">
export interface Person {
  name: string;
}

const props = defineProps<{
  person: Person;
}>();

function onClick(): void {
  props.person.name = 'Joe'; // mutate nested field
}
</script>

<template>
  <button @click="onClick">Click</button>
</template>

如何防止嵌套属性字段的突变?

wlzqhblo

wlzqhblo1#

你可以使用readonly修饰符使props成为只读的。这将确保 prop 不能在组件内发生变化。

<script setup lang="ts">
export interface Person {
  name: string;
  address: {
    city: string;
    street: string;
  };
}

type DeepReadonly<T> = {
  readonly [K in keyof T]: DeepReadonly<T[K]>;
};

const props = defineProps<{
  person: DeepReadonly<Person>;
}>();

function onClick(): void {
  // TypeScript error: Cannot assign to 'name' because it is a read-only property
  props.person.name = 'Joe';

  // TypeScript error: Cannot assign to 'city' because it is a read-only property
  props.person.address.city = 'New City';
}
</script>

<template>
  <button @click="onClick">Click</button>
</template>

相关问题