Vue3 props: `required: true` 与 vant 的`makeRequiredProp`

为什么直接加 required: true会报错,用了makeRequiredProp就不会了?

makeRequiredProp 源码:

typescript 复制代码
export const makeRequiredProp = <T>(type: T) => ({
  type,
  required: true as const,
});
  • 原因

    • 写成 { type: [Number, String], required: true } 时,TS 会把 type 推断为 (NumberConstructor | StringConstructor)[],在 Vue 的 ExtractPropTypes 推断里,常见情形会丢失"必填"约束,结果在组件里 props.xxx 仍被认为可能是 undefined
    • makeRequiredProptype 明确成预期的 PropType,并且 required 是字面量 true(true as const);这样 ExtractPropTypes 才会把该 prop 标记为非可选,消除 "possibly undefined"。
  • 简洁可行的两种写法

    • 用 helper(推荐):

      ts 复制代码
      import { makeRequiredProp, numericProp } from '../utils/props'
      
      optionHeight: makeRequiredProp(Number),
      swipeDuration: makeRequiredProp(numericProp),
      fields: makeRequiredProp(Object as PropType<Required<PickerFieldNames>>),
    • 或者手工写到位(注意 as const 与 PropType):

      ts 复制代码
      optionHeight: { type: Number as PropType<number>, required: true as const },
      swipeDuration: { type: numericProp as PropType<number | string>, required: true as const },
      fields: { type: Object as PropType<Required<PickerFieldNames>>, required: true as const },

这两种方式都能让 TS 正确认定为必填,避免 props.xxx 的 undefined 报警。

相关推荐
程序员龙语23 分钟前
CSS 高级选择器应用
前端·css
Cassie燁24 分钟前
el-table源码解读2-2——createStore()初始化方法
前端·javascript·vue.js
程序员修心26 分钟前
CSS文本样式全解析:11个核心属性详解
前端·css
旧梦吟1 小时前
脚本网站 开源项目
前端·web安全·网络安全·css3·html5
我有一棵树1 小时前
解决 highlight.js 不支持语言的方法
开发语言·javascript·ecmascript
北极糊的狐1 小时前
按钮绑定事件达成跳转效果并将树结构id带入子页面形成参数完成查询功能并将返回的数据渲染到页面上2022.5.29
前端·javascript·vue.js
幽络源小助理1 小时前
幽络源二次元分享地址发布页源码(HTML) – 源码网免费分享
前端·html
全栈前端老曹1 小时前
【ReactNative】页面跳转与参数传递 - navigate、push 方法详解
前端·javascript·react native·react.js·页面跳转·移动端开发·页面导航
用泥种荷花2 小时前
【前端学习AI】Python环境搭建
前端
老华带你飞2 小时前
考试管理系统|基于java+ vue考试管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端