最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Typescript displays error for "this" Object saying TS2532: Object is possibly 'undefined&

programmeradmin3浏览0评论

As I am still fairly new to writing questions, I apologise for possible misvoicing.

The problem: I have a vue app with typescript.

export default {
    methods: {
        setProgram: (program: Program)=>{
            this.program = program // TS2532: Object is possibly 'undefined'.
            this.step++ // TS2532: Object is possibly 'undefined'.
        }
    },
    ...
}

While I really like this feature of typescript, I really am sure, that "this" will not be undefined in this case.

How can I calm typescript down regarding the use of "this"?

Thank you very much everyone, have a great day ahead!

Best Dom.

As I am still fairly new to writing questions, I apologise for possible misvoicing.

The problem: I have a vue app with typescript.

export default {
    methods: {
        setProgram: (program: Program)=>{
            this.program = program // TS2532: Object is possibly 'undefined'.
            this.step++ // TS2532: Object is possibly 'undefined'.
        }
    },
    ...
}

While I really like this feature of typescript, I really am sure, that "this" will not be undefined in this case.

How can I calm typescript down regarding the use of "this"?

Thank you very much everyone, have a great day ahead!

Best Dom.

Share Improve this question edited Nov 24, 2021 at 23:28 Phil 165k25 gold badges261 silver badges267 bronze badges asked Nov 24, 2021 at 22:45 Dominik ZiDominik Zi 4435 silver badges14 bronze badges 8
  • TypeScript Support - Basic Usage – Phil Commented Nov 24, 2021 at 22:53
  • Yep, already set the remended configuration. Still doesn't work ... – Dominik Zi Commented Nov 24, 2021 at 23:00
  • I specifically meant the Vue.extend({ ... }) bit, ie export default Vue.extend({ methods: { ... } }) – Phil Commented Nov 24, 2021 at 23:06
  • Okay, just tried that. Unfortunately still the same ... – Dominik Zi Commented Nov 24, 2021 at 23:12
  • I mean even if I did if(this!=undefined) this.program = program it will give me this error ... – Dominik Zi Commented Nov 24, 2021 at 23:24
 |  Show 3 more ments

1 Answer 1

Reset to default 15

Got it!

"this" might be undefined if used inside lambda function :)

just change

setProgram: (program: Program) => {

to:

setProgram: function (program: Program) {

and it works ...

发布评论

评论列表(0)

  1. 暂无评论