J
J
Juniorrrrr2021-10-07 11:50:13
typescript
Juniorrrrr, 2021-10-07 11:50:13

How to pass a function argument, for a complex object?

There is a complex object

const obj:DataType = {
  val0:boolean,
  val1:string,
  val2:null | undefined | string
  val3: {
    field0:[string, string]
    field1: {
      word:string
    },
  val4:[
    {text0: true, text2:{}}
  ]  
  }
}


I want to write a function that will change values ​​by key. Something like this
function changeField(data:DataType, fieldName:keyof DataType, val:any) {
  data[fieldName] = val
}


But at the time of assignment I get an error the type any cannot be assigned to the type never
I understand that this error is just related to the fact that val has type any
Please tell me if there is any relatively simple solution?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2021-10-07
@Juniorrrrr

function changeField<T extends DataType, K extends keyof T>(data:T, fieldName:K, val: T[K]) {
  data[fieldName] = val
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question