我正在尝试一个函数,它将索引作为参数,其中键被限制为T的键
function aliasSet<T>(values: {[x:keyof T]:string})
//compiler error: An index signature parameter type must be 'string' or 'number'有什么办法可以做到这一点吗?这是正确的方法吗?
发布于 2019-05-23 18:50:08
索引签名参数只能为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: ""
})https://stackoverflow.com/questions/56273520
复制相似问题