Obiwahn
Obiwahn

Reputation: 3087

Accessing object property key on assignment

class Item {
    prop:Field;

    constructor() {
        this.prop = this.createField("prop", defaultValue);
    }
}

Is there a way to derive the property key on assignment (in the cerateField method). I want to omit the "prop" parameter (which I need for the database field name).

Upvotes: 1

Views: 81

Answers (1)

tscpp
tscpp

Reputation: 1586

I would suggest using decorators. Unfortunately, decorators can not convert the type of a property, so the alternative is using decorators in combination with a type converting function, which i named field with a lowercase "f". The function is essentially just an empty function forcing the type because the decorator is unable to. The decorator Field is doing the actual value converting using the function createField with setters and getters.

function Field(target: any, propKey: string) {
    Object.defineProperty(target, propKey, {
        configurable: true,
        set(value: any) {
            Object.defineProperty(this, propKey, {
                enumerable: true,
                value: createField(propKey, value)
            })
        }
    })
}

function field<T>(defaultValue: T) {
    return defaultValue as unknown as Field<T>
}

class Item {
    @Field
    prop = field(defaultValue)
}

// This could also be shortened to

class Item {
    @F prop = field(...)
}

Upvotes: 1

Related Questions