From 2b8451aefe68702a7cd2a523f95dc03445415171 Mon Sep 17 00:00:00 2001 From: Eemeli Aro Date: Sat, 27 Mar 2021 16:55:25 +0200 Subject: [PATCH] fix: Use different workaround for overriding properties in Pair (Fixes #245) --- src/nodes/Pair.ts | 57 +++++++++++++++++++++++------------------------ 1 file changed, 28 insertions(+), 29 deletions(-) diff --git a/src/nodes/Pair.ts b/src/nodes/Pair.ts index 33890129..02542109 100644 --- a/src/nodes/Pair.ts +++ b/src/nodes/Pair.ts @@ -27,36 +27,35 @@ export class Pair extends NodeBase { super(PAIR) this.key = key this.value = value - } - - // @ts-ignore This is fine. - get commentBefore() { - return isNode(this.key) ? this.key.commentBefore : undefined - } - - set commentBefore(cb) { - if (this.key == null) this.key = new Scalar(null) as any // FIXME - if (isNode(this.key)) this.key.commentBefore = cb - else { - const msg = - 'Pair.commentBefore is an alias for Pair.key.commentBefore. To set it, the key must be a Node.' - throw new Error(msg) - } - } - - // @ts-ignore This is fine. - get spaceBefore() { - return isNode(this.key) ? this.key.spaceBefore : undefined - } - set spaceBefore(sb) { - if (this.key == null) this.key = new Scalar(null) as any // FIXME - if (isNode(this.key)) this.key.spaceBefore = sb - else { - const msg = - 'Pair.spaceBefore is an alias for Pair.key.spaceBefore. To set it, the key must be a Node.' - throw new Error(msg) - } + // TS doesn't allow for accessors to override properties + // https://github.com/microsoft/TypeScript/pull/33509 + Object.defineProperties(this, { + commentBefore: { + get: () => (isNode(this.key) ? this.key.commentBefore : undefined), + set: (cb: string | null) => { + if (this.key == null) this.key = (new Scalar(null) as unknown) as K + if (isNode(this.key)) this.key.commentBefore = cb + else { + const msg = + 'Pair.commentBefore is an alias for Pair.key.commentBefore. To set it, the key must be a Node.' + throw new Error(msg) + } + } + }, + spaceBefore: { + get: () => (isNode(this.key) ? this.key.spaceBefore : undefined), + set: (sb: boolean) => { + if (this.key == null) this.key = (new Scalar(null) as unknown) as K + if (isNode(this.key)) this.key.spaceBefore = sb + else { + const msg = + 'Pair.spaceBefore is an alias for Pair.key.spaceBefore. To set it, the key must be a Node.' + throw new Error(msg) + } + } + } + }) } toJSON(_?: unknown, ctx?: ToJSContext): ReturnType {