我有这个TypeScript类:
export class UserCredentials {
public name: string;
static getName() {
return this.name;
}
}
当我删除static
时,一切正常。但有了它,我有以下编译器错误:Property 'name' does not exist on type 'typeof UserCredentials'
。
答案 0 :(得分:1)
在静态方法中,您无法访问“this”实例或其属性。 使用“静态”修改器标记您的字段以使其起作用:
public static name: string;
答案 1 :(得分:0)
在这种情况下,您仅必须(如果您不希望使属性'name'成为静态的)在静态方法中创建新实例
export class UserCredentials {
public name: string;
static getName() {
const userCredentials = new UserCredentials(); // <--- create this
return userCredentials.name;
}
}