Skip to content

Commit

Permalink
fix: Use different workaround for overriding properties in Pair (Fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
eemeli committed Mar 27, 2021
1 parent 5ec323c commit 2b8451a
Showing 1 changed file with 28 additions and 29 deletions.
57 changes: 28 additions & 29 deletions src/nodes/Pair.ts
Expand Up @@ -27,36 +27,35 @@ export class Pair<K = unknown, V = unknown> 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<typeof addPairToJSMap> {
Expand Down

0 comments on commit 2b8451a

Please sign in to comment.