Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript function with argument of type property of Interface

Is there a way to use a property/key of an interface as a function argument type?

For example, if I have an interface:

interface column{
   id: string,
   title: string,
   description: string
}

and I have a function:

const replaceColumnProperty = (col: column, property: string, val: string) => {
   col[property] = val;
}

Typescript complains that type string does not match column interface.

It should be:

const replaceColumnProperty = (col: column, property: 'id' | 'title' | 'description', val: string) => {
   col[property] = val;
}

However, my interface has 20 properties. Is there a way to avoid having to write a constant for each interface property?

like image 511
DeltaTango Avatar asked Oct 24 '25 23:10

DeltaTango


1 Answers

Yes, you can use the keyof type operator to get a union of the keys of an object-like type:

const replaceColumnProperty = (col: Column, property: keyof Column, val: string) => {
  col[property] = val; // okay
}

And you can verify it works the way you want from the call side too:

const col = { id: "", title: "", description: "" }
replaceColumnProperty(col, "id", "id"); // okay
replaceColumnProperty(col, "oops", "oops"); // error!
// ----------------------> ~~~~~~
// Argument of type '"oops"' is not assignable to parameter of type 'keyof Column'.

Playground link to code

like image 147
jcalz Avatar answered Oct 26 '25 16:10

jcalz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!