简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM