【问题标题】:How can I create an Array that has its values as its type?如何创建一个将其值作为其类型的数组?
【发布时间】:2021-05-27 05:13:26
【问题描述】:

如何在不重复Array类型的key的情况下编写如下逻辑?

type UserFillable = [
  'first_name',
  'last_name',
  'email',
  'sector',
]

export default class User {
  public static readonly fillable: UserFillable = [
    'first_name',
    'last_name',
    'email',
    'sector',
  ]
}

另一个例子是......

export default class User {
  public static readonly fillable = [
    'first_name',
    'last_name',
    'email',
    'sector',
  ] as [
    'first_name',
    'last_name',
    'email',
    'sector',
  ]
}

【问题讨论】:

    标签: javascript arrays typescript types


    【解决方案1】:

    我建议您使用const assertion 让编译器推断出您正在初始化的属性的最具体类型:

    export default class User {
        public static readonly fillable = [
            'first_name',
            'last_name',
            'email',
            'sector',
        ] as const
    }
    

    这将自动成为您要查找的 string literal types 中的 readonly tuple

    // (property) User.fillable: readonly 
    //   ["first_name", "last_name", "email", "sector"]
    

    您可能不再需要定义 UserFillable 类型,但如果您这样做了,最好按照 User.fillable 来定义,反之亦然:

    type UserFillable = typeof User.fillable;
    

    Playground link to code

    【讨论】:

    • 非常感谢!虽然此解决方案不适用于我的用例(传递 readonly 值是不可能的,因为它需要 string[] 类型),但它肯定回答了我的问题!
    • 如果您无法处理readonly,您可以使用辅助函数将readonly“提升”为可变值,例如this
    猜你喜欢
    • 1970-01-01
    • 2019-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-14
    • 1970-01-01
    • 1970-01-01
    • 2011-10-15
    相关资源
    最近更新 更多