Guarding type when class property is symbol?

后端 未结 1 767
走了就别回头了
走了就别回头了 2021-01-29 03:34

I was looking to use a symbol for a property, but I realize because I\'m using this[SYM] syntax, I can\'t get guarding to work properly. I was wondering if there wa

相关标签:
1条回答
  • 2021-01-29 04:01

    Narrowing the type of an accessed property does not narrow the type of the parent object. So checking this[SYM] doesn't tell TS anything, because it's not in a standalone variable. That's why extracting the value into v works - it's a standalone variable, so it can be narrowed.

    A more concise version would be:

    const SYM = Symbol('SYM');
    class Example {
      [SYM]?: string;
      get prop() {
        return this[SYM] ?? 'default';
      }
    }
    

    No need to explicitly annotate the return value of prop once your typings are correct.

    0 讨论(0)
提交回复
热议问题