Search code examples
typescripttyping

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:

const foo = (arg: IExample.b): void => {  // this generates an error
  //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