正在访问分配时的对象属性键


class Item {
prop:Field;
constructor() {
this.prop = this.createField("prop", defaultValue);
}
}

有没有一种方法可以在赋值时派生属性键(在cerateField方法中(。我想省略"prop"参数(我需要它作为数据库字段名(。

我建议使用装饰器。不幸的是,decorator无法转换属性的类型,因此另一种选择是将decorator与类型转换函数结合使用,我用小写字母"将其命名为field;f";。该函数本质上只是一个强制类型的空函数,因为decorator不能。decoratorField使用带有setter和getter的函数createField进行实际值转换。

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(...)
}

最新更新