1

In Typescript, I have a function:-

   function updateSetting(settingName, settingValue: string[]| number | null) { 
      this.props.updateSetting({[settingName]}: settingValue)
  }

and i also have a object, so i have an interface for it

   interface Setting {
      names: string[]
      city: string | null
      age: number
   }

So, i want to use object as an argument, and i also want that one of the property of the object is passed as an argument which is decided at the run time. So in my function settingName can be either 'name' or 'city' or 'age', so i want to assign the type from the interface itself.

I don't want to write (settingValue: string[]| number | null) i want to write something like

settingValue: valueof Setting

because setting value can be any of the type names, city, age.

How can i achieve this in typescript ?

1

2 Answers 2

3

if you want to set type of settingValue and your interface dynamicaly you can try:

settingValue: Setting[keyof Setting]; // string[]| number | null

or if you want keys of setting it without their types:

settingValue = keyof Setting ; // names| city | age
Sign up to request clarification or add additional context in comments.

Comments

3

You can improve your function more then just the type of settingValue you can also ensure the settingName and settingValue are consistent:

function updateSetting<TKey extends keyof Setting>(settingName: TKey, settingValue: Setting[TKey]) {
    //...
}

interface Setting {
    names: string[]
    city: string | null
    age: number
}

updateSetting("names", [""])
updateSetting("age", [""]) //error

We use the keyof operator to specify that the generic parameter Tkey must be a string literal type that is one of te keys of Setting then we specify that settingValue must have whatever type the field of Setting has for the given key using a type query Setting[TKey]

This approach ensures more type safety if you use it with constant keys usually. If you want to pass an arbitrary string you will need to use a type assertion, and the type of settingValue will be the same as Setting[keyof Setting]:

let str;
updateSetting(str as keyof Setting, 0) //ok
updateSetting(str as keyof Setting, new Date()) //error

1 Comment

This was exceptionally helpful. I had no idea how to google this, but stumbled across this answer and it's perfect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.