【问题标题】:Enforce boundaries of key in an index强制索引中键的边界
【发布时间】:2019-10-09 22:16:00
【问题描述】:

我正在尝试使用一个将索引作为参数的函数,其中键被限制为 T 的键

function aliasSet<T>(values: {[x:keyof T]:string})
//compiler error: An index signature parameter type must be 'string' or 'number'

有没有办法做到这一点?这是正确的方法吗?

【问题讨论】:

    标签: typescript generics keyof


    【解决方案1】:

    索引签名参数只能是numberstring(甚至不能是number | string

    您正在寻找映射类型,特别是 Record 映射类型:

    function aliasSet<T>(values: Record<keyof T, string>)
    

    例如:

    declare function aliasSet<T>(values: Record<keyof T, string>) : void;
    interface O {
        foo: number,
        bar?: boolean
    }
    
    aliasSet<O>({
        bar: "", // Record erases optionality, if you want all to be optional you can use Partial<Record<keyof T, string>>
        foo: ""
    })
    

    【讨论】:

    • 太好了,就是这样!我在文档中看到 Record 但不太确定如何使用它。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-07-13
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多