4

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?

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

Comments

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.