Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to define a function's argument type as one of the keys (or properties) of an interface

Given any interface, is there a way to say that a variable’s type is one of the keys in that interface?

Suppose you have this interface:

interface IExample {
  a: string;
  b: {
    b1: string;
    b2: string | number | boolean;
  };
}

And you have a function like:

const foo = (arg) => {
  //function's logic 
}

Now I want to type arg as being b from IExample, something like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const foo = (arg: IExample.b): void => {
  //function's logic 
}

To be clear, the function’s argument should be:

{
  b1: string;
  b2: string | number | boolean;
}

and I didn’t want to have to write another interface just for that.

I couldn’t find a way by myself, neither figure it out by reading the typescript docs. This is my last hope.

>Solution :

You use [] to index types. Some documentation on this is here.

function foo(arg: IExample['b']): void {
  //function's logic 
}

foo({ b1: 'abc', b2: true })

See Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading