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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With