我有一个 User 类,它有一个装饰属性“name”。我试图使用 Object.assign 在父类(基)构造函数中初始化此属性,但该值是“未定义”。当我删除装饰器时,该属性将使用正确的值进行初始化。请参阅下面的代码 - 我使用 typescript 版本 5.4.2。
有人可以帮我吗?有什么办法可以让这个工作吗?
谢谢。
// test.ts
(Symbol as any).metadata ??= Symbol("Symbol.metadata") // Polyfill
function Value(value: string) {
return (_target: any, context: ClassFieldDecoratorContext) => {
context.metadata[context.name] = value
}
}
class Base {
constructor(data: any) {
Object.assign(this, data)
}
}
interface IUser {
id: string
name?: string
}
class User extends Base implements IUser {
id: string
constructor(data: IUser) {
super(data)
}
@Value("test")
name?: string
}
const data = {
id: "1",
name: "John Doe"
}
const user = new User(data)
// user.id is 1
// user.name is undefined
通过将
id
设为可选来修复错误,现在已填充两个属性。
// test.ts
(Symbol as any).metadata ??= Symbol("Symbol.metadata") // Polyfill
function Value(value: string) {
return (_target: any, context: ClassFieldDecoratorContext) => {
context.metadata![context.name] = value
}
}
class Base {
constructor(data: any) {
Object.assign(this, data)
}
}
interface IUser {
id?: string
name?: string
}
class User extends Base implements IUser {
id?: string
constructor(data: IUser) {
super(data)
}
name?: string
}
const data = {
id: "1",
name: "John Doe"
}
const user = new User(data)
console.log(user)
// user.id is 1
// user.name is undefined