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
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.