You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Hook Form:useWatch传枚举数组遇TS错误,求类型安全实现方案

问题

我希望在组件中监听表单的部分字段,并且传入固定顺序的常量数组,确保整个应用内字段顺序一致,方便追踪哪些字段已更新。

尝试用枚举实现时出现TypeScript错误:

export enum FieldsToWatch {
    "firstField",
    "secondField",
}

const fieldsBeingWatched = useWatch({
    control,
    name: Object.keys(FieldsToWatch),
});

错误提示:

TS2769: No overload matches this call.

直接传入字面量数组['firstField', 'secondField']能正常编译,但我想要类型安全的写法,该怎么实现?

解决方案

方法1:使用as const定义常量数组(推荐)

用as const断言定义只读常量数组,既能保证类型安全,又能固定字段顺序:

export const FIELDS_TO_WATCH = ['firstField', 'secondField'] as const;

const fieldsBeingWatched = useWatch({
    control,
    name: FIELDS_TO_WATCH,
});

优势:

  • 数组元素为字面量类型,TypeScript会严格校验字段名合法性
  • as const确保数组不可修改,顺序固定
  • 写法简洁,无额外类型转换成本

方法2:兼容枚举的写法(若必须用枚举)

如果坚持使用枚举,需要给枚举成员显式赋值,再通过Object.values获取字段名数组并做类型断言:

export enum FieldsToWatch {
    firstField = 'firstField',
    secondField = 'secondField',
}

const fieldsBeingWatched = useWatch({
    control,
    name: Object.values(FieldsToWatch) as ['firstField', 'secondField'],
});

注意:如果不给枚举成员显式赋值,默认是数字枚举,Object.values会返回数字数组,不符合表单字段名的需求。

方法3:结合类型与常量数组(兼顾类型定义和常量)

如果需要同时定义字段类型和固定顺序的常量数组,可以用satisfies关键字做类型校验:

// 定义字段联合类型
export type FieldsToWatch = 'firstField' | 'secondField';
// 定义常量数组,确保元素符合类型且顺序固定
export const FIELDS_TO_WATCH = ['firstField', 'secondField'] as const satisfies readonly FieldsToWatch[];

const fieldsBeingWatched = useWatch({
    control,
    name: FIELDS_TO_WATCH,
});

内容的提问来源于stack exchange,提问作者Leff

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 00:07:12