typescript - 为 TypeScript 使用 @Prop 装饰器 - 编译器给出错误要求初始化 prop

标签 typescript vue.js vuejs2 vue-component tslint

我将 Vue 与 TypeScript 和 vue-property-decorator 包一起使用。

当我像这样使用 Prop 时:

@Prop({ default: '' }) private type: string

我得到一个 TS 编译器错误:Property 'type' has no initializer and is not definitely assigned in the constructor.

但是如果我用类似的东西初始化它:

@Prop({ default: '' }) private type: string = ''

然后我在浏览器控制台中收到警告:

vue.runtime.esm.js?ff9b:587 [Vue warn]: Avoid mutating a prop directly since the value will be overwritten 
whenever the parent component re-renders. Instead, use a data or computed property based on the prop's 
value. Prop being mutated: "type"

那么在这种情况下我应该怎么做才能没有任何错误或警告?

我唯一能想到的是在 tsconfig.json 中设置:"strictPropertyInitialization": false,但我想尽可能避免这种情况。

谢谢!

最佳答案

初始错误消息是 TypeScript 的严格类初始化(在 2.7 中引入)的结果。 2.7 的发行说明描述了使用 definite assignment operator (!) 来解决这个问题。在你的情况下,你会这样做:

@Prop({ default: '' }) private type!: string

关于typescript - 为 TypeScript 使用 @Prop 装饰器 - 编译器给出错误要求初始化 prop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50422006/

相关文章:

Typescript:如何检查一个值是否是有效的 Enum 键值?

angular - 如何将一种类型的 Observable 转换为另一种类型的 Observable

vue.js - 类型错误 : Cannot read properties of null (reading 'isCE' ) - Custom Component Library

javascript - 在另一个属性中引用元素属性

javascript - Vue.js "npm run build"但 Vue.js 未绑定(bind)到 DOM/工作

javascript - 路由器导出的 Angular 2 延迟渲染

vue.js - 在哪里可以编辑 modal vue coreui 的页脚?

javascript - Vue JS 设置要选择的填充选择中的第一项

javascript - 在 Vuejs 中使用谷歌地图标记集群

typescript - 如何使用任意键声明类型化对象?