TypeScript · Senior · Question 8 of 75

How do you keep only the function-valued properties of a type?

type Methods<T> = {
  [K in keyof T as T[K] extends Function ? K : never]: T[K];
};

Explanation

If the expression after as evaluates to never, the key is dropped. It's the standard technique for filtering keys by value type. Without as, you'd first compute the union of keys and then apply Pick.

Further reading

Problem with a question

TypeScript · Senior · question 8

Test yourself

Take the TypeScript · Senior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz