0

I am trying to have a function that takes an index as parameter where the key is limited to a key of T

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

Is there anyway to achieve that? Is this the right approach?

Yooz
  • 2,506
  • 21
  • 31

1 Answers1

2

Index signature parameters can only be number or string (not even number | string)

You are looking for mapped types, specifically for the Record mapped type:

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

Ex:

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: ""
})
Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357
  • Great, that's it! I saw Record in the documentation but was not quite sure how to use it. Thanks for that! – Yooz May 23 '19 at 10:56