1

Given an interface like this:

interface IDelegates {
  delegateOne: (name: string, age: number) => string;
  delegateTwo: (date: Date) => number;
}

How to define a method that takes in a func of the correct delegate type, based on the interface property name?

I can get a type with just the property I want using Pick<IDelegates, 'delegateOne'> which returns a type:

{
  delegateOne: (name: string, age: number) => string;
}

But I can't then figure out if there is a way to do Parameters<Pick<IDelegates, 'delegateOne'>>

I get why this doesn't work, but thinging there might be a way? Basically I'd need PickOne or something, to return just the property 'delegateOne', rather than a type containing the property.

1 Answer 1

7

Instead of using Pick<T, K>, you want lookup types, which are actually simpler. If you have an object type T and a key type K which is assignable to keyof T, then the type of the property of T with key K is: T[K]. So you use the familiar bracket index access notation, but at the type level.

(Aside: Note that you cannot use dot notation for lookup types, even if K is a string literal type. For example, you need to write type Array<string>["length"] to get number and not Array<string>.length. The dot is already used at the type level for namespacing, so they don't want to introduce ambiguity and possible name collisions with allowing the same notation to represent two different type operations.)

Lookup types are, not coincidentally, used in the definition of Pick<T, K> to grab each property of T in the set of keys in K:

type Pick<T, K extends keyof T> = {
    [P in K]: T[P]; // T[P] is the type of property of T with key P
};

Anyway, that means you should do this:

type ThingYouWant = Parameters<IDelegates["delegateOne"]>;
// type ThingYouWant = [string, number]

Okay, hope that helps. Good luck!

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.