From f6de25c41334e884ce8ee2dc20f0b6c9d3565bbc Mon Sep 17 00:00:00 2001 From: Chen Yangjian <252317+cyjake@users.noreply.github.com> Date: Mon, 26 Sep 2022 21:33:04 +0800 Subject: [PATCH] fix: this.attribute(name) should fallback to Literal ```ts class Foo { @Column(TEXT) get settings(): Record { // this.attribute('settings') should return the original union type here const text = this.attribute('settings') as string; if (!text) return null; try { return JSON.parse(text); } catch { return null; } } } ``` --- src/types/abstract_bone.d.ts | 6 +++--- test/types/basics.test.ts | 19 ++++++++++++++++++- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/src/types/abstract_bone.d.ts b/src/types/abstract_bone.d.ts index 68dcca39..eec3c321 100644 --- a/src/types/abstract_bone.d.ts +++ b/src/types/abstract_bone.d.ts @@ -241,15 +241,15 @@ export class AbstractBone { * bone.attribute('foo'); // => 1 * bone.attribute('foo', 2); // => bone */ - attribute(this: T, name: Key, value: T[Key]): void; - attribute(this: T, name: Key): T[Key]; + attribute(this: T, name: Key, value: Literal): void; + attribute(this: T, name: Key): U extends Literal ? U : Literal; /** * Get the original attribute value. * @example * bone.attributeWas('foo') // => 1 */ - attributeWas>(this: T, key: Key): T[Key]; + attributeWas, U extends T[Key]>(this: T, key: Key): U extends Literal ? U : Literal; /** * See if attribute has been changed or not. diff --git a/test/types/basics.test.ts b/test/types/basics.test.ts index 861469b7..91b0cea8 100644 --- a/test/types/basics.test.ts +++ b/test/types/basics.test.ts @@ -48,7 +48,20 @@ describe('=> Basics (TypeScript)', function() { summary: string; @Column(TEXT) - settings: string; + get settings(): Record { + const text = this.attribute('settings') as string; + if (!text) return null; + try { + return JSON.parse(text); + } catch { + return null; + } + } + + set settings(value: string | Record) { + if (typeof value !== 'string') value = JSON.stringify(value); + this.attribute('settings', value); + } @Column() wordCount: number; @@ -81,12 +94,16 @@ describe('=> Basics (TypeScript)', function() { it('bone.attribute(name)', async function() { const post = await Post.create({ title: 'Cain' }); assert.equal(post.attribute('title'), 'Cain'); + assert.equal(post.attributeWas('title'), 'Cain'); + assert.equal(post.attribute('settings'), null); }); it('bone.attribute(name, value)', async function() { const post = new Post({}); post.attribute('title', 'Cain'); + post.attribute('settings', '{"foo":1}'); assert.equal(post.title, 'Cain'); + assert.deepEqual(post.settings, { foo: 1 }); }); it('bone.changed()', async function() {