vue 进行 props 类型检查用 instanceof 不会有问题吗?

阅读 977
avatarAI BotBETA

在Vue 3中,使用defineProps函数定义props时,使用instanceof进行类型检查是不会有问题的。

这是因为defineProps函数返回的对象中,每个prop都是一个具有特定类型(例如Array或String等)的属性,因此您可以放心地使用instanceof运算符来检查prop的类型。

例如,以下代码段演示了如何使用instanceof来检查props.name是否为Array类型:

const props = defineProps({
  name: Array
});

if (props.name instanceof Array) {
  console.log('props.name is an instance of Array');
} else {
  console.log('props.name is not an instance of Array');
}

在此代码段中,如果传递给prop的值为数组,则控制台将打印出“props.name is an instance of Array”。否则,它将打印出“props.name is not an instance of Array”。

此外,您还可以使用其他方法来检查prop的类型,例如使用Array的isArray方法:

const props = defineProps({
  name: Array
});

Array.isArray(props.name) // true

总之,在Vue 3中,使用defineProps定义的props类型是可靠的,并且可以使用常规的类型检查方法来验证它们。

2 个回答

不能说毫无风险。
但风险并不在于你说的这一点,你列举的这一类问题会在框架层面得到解决,不会把烂摊子留给开发者。亲手实现过深度拷贝的人大抵都知道必须先检测是否为 RegExpArrayDate 等内置对象,确定不是这些对之后,才能按照 Object 来处理,框架的解决方案应该与此类似。
incetanceof 检测存在的可能风险在于 JS 写法过于灵活,以至于子类属性与超类的同名属性可以不兼容,incetanceof并不能检测出这种改动

class TaniedArray extends Array{
  forEach(){
    return null
  }

  get map(){
    return null
  }
}
const taniedArray = new TaniedArray(1,2,3,4,5);
console.log(taniedArray incetanceof Array);
// true
taniedArray.map(i=>i); // 报错
👆 这里子类的 forEachmap 与超类的同名方法不同(map甚至已经不再是方法了),假如 Vue 试图调用taniedArray.map,就会报错。
这种改动难以检测,即便使用 AI 推荐的 Array.isArray 方法来检测,依旧无法发现问题。

对 JS 而言,这种问题是无解的,因为这种改动难以约束,也那一检测,因此避免这种问题,只能指望开发者自己不要乱来。

会有的,instanceof是差对象的原型链上是否有改类型,有就会返回true

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题