对TypeScript使用@Prop修饰符 - 编译器给出了初始化prop的错误

时间:2018-05-19 05:14:19

标签: typescript vue.js vuejs2 vue-component tslint

我正在使用带有TypeScript和vue-property-decorator包的Vue。

当我使用这样的道具时:

@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,但如果可能的话,我想避免这种情况。

谢谢!

1 个答案:

答案 0 :(得分:2)

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

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