处理各处的 TypeScript DeepReadonly 状态

问题描述 投票:0回答:1

我使用简单的 Vue 3 Composition API 存储来集中模块的状态。经过推荐的良好实践后,状态将导出为只读,以防止来自外部的不必要的状态突变,只能通过同一存储导出的方法进行可变。

import { reactive, readonly } from 'vue';

const state = reactive<State>({
  /* whatever here */
});

export default readonly(state);

/* Export methods to mutate state */

此后,我的状态类型在各处都以只读方式深度嵌套。从现在开始,我需要将 DeepReadonly 修饰符添加到使用状态的每个函数参数、reducer 或组件 prop 中,特别是当函数调用链也变得很深时。老实说,处理它已经成为一项艰巨的任务。

更不用说将状态作为参数传递给不接受 DeepReadonly 的第三方函数。即使尝试强制转换它,TypeScript 也会抱怨可变类型无法分配给不可变值。

处理这个问题的正确方法是什么?如果找不到方法,我正在认真考虑删除只读保护。

typescript vue.js types readonly-attribute
1个回答
0
投票

您可以使用

DeepReadonly
UnwrapNestedRefs
两者都可以在
vue
中导入:

import type { DeepReadonly, Ref, UnwrapNestedRefs } from 'vue';

DeepReadonly<UnwrapNestedRefs<Ref<User[]>>>

更多信息https://vuejs.org/api/reactivity-core.html#readonly

© www.soinside.com 2019 - 2024. All rights reserved.