在索引中强制执行键的边界
Enforce boundaries of key in an index
我正在尝试使用一个将索引作为参数的函数,其中键被限制为 T
function aliasSet<T>(values: {[x:keyof T]:string})
//compiler error: An index signature parameter type must be 'string' or 'number'
有什么方法可以实现吗?这是正确的方法吗?
索引签名参数只能是number
或string
(甚至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: ""
})
我正在尝试使用一个将索引作为参数的函数,其中键被限制为 T
function aliasSet<T>(values: {[x:keyof T]:string})
//compiler error: An index signature parameter type must be 'string' or 'number'
有什么方法可以实现吗?这是正确的方法吗?
索引签名参数只能是number
或string
(甚至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: ""
})