【问题标题】:Typescript type for getting class properties from static method on a parent class用于从父类的静态方法获取类属性的打字稿类型
【发布时间】:2020-06-03 07:43:59
【问题描述】:

假设你有这两个类:

class Form {
    static fields(){
       return []; // some magic happens here
    }
}

class UserForm extends Form{
    email: string;
}

const formFields = UserForm.fields();

我可以为静态fields 方法添加什么类型以获取UserForm 属性列表,在这种情况下,只有电子邮件属性为("email")[]

我尝试使用keyof T,但它没有给我想要的答案:

static fields<T>(this: T): (keyof T)[] {
       return []; // some magic happens here
    }

这将返回 ("prototype" | "fields")[] 而不是 ("email")[]

您对如何解决这个问题有任何想法吗?

谢谢!

【问题讨论】:

    标签: typescript class oop types


    【解决方案1】:

    您可以创建this 的新实例并返回Object.getOwnPropertyNames(instance)

    class Form {
        foo: string = 'bar'
        static fields<T>(): (keyof T)[]{
           return Object.getOwnPropertyNames(new this) as (keyof T)[]
        }
    }
    
    class UserForm extends Form{
        email: string = '';
    }
    
    const formFields = UserForm.fields<UserForm>();
    console.log(formFields)
    

    工作 repl.it 项目:https://repl.it/@HarunYlmaz/ts-property-list

    【讨论】:

    • 是的,但是该方法的确切类型是什么?从你的代码我看到它是string[]。我不希望 fields() 方法返回 string[]。我想要确切的字段。喜欢("email" | "foo")[]
    • 你想让方法返回属性的类型吗?
    • 没有。我只想让方法返回当前类的属性/字段
    • 此解决方案返回类属性的名称。我想我没有完全理解你想要得到的结果。
    • 我希望方法的类型显示字段名称。我真的不在乎方法返回什么。我想设置方法的类型来返回一个类的字段。
    猜你喜欢
    • 2019-08-11
    • 1970-01-01
    • 2021-08-13
    • 2017-03-03
    • 2021-05-16
    • 2021-12-14
    • 2020-04-20
    • 1970-01-01
    • 2020-04-23
    相关资源
    最近更新 更多