01 / 06

How to type annotate functions?

TypeScript allows you to specify the types of both the input and output values of functions.

Parameter Type Annotations When you declare a function, you can add type annotations after each parameter to declare what types of parameters the function accepts.
Type annotation for multiple parameters
Return Type Annotations You can also add return type annotations. Return type annotations appear after the parameter list:
Difficulty: 5/10
Topics: function signatures, generic types, overloads

Scenario Questions

0-2 years experience
  1. 1

    We have a simple utility function function add(a, b) { return a + b; }. How would you add TypeScript annotations so that it only accepts numbers and returns a number?

  2. 2

    If you forget to annotate the return type of a function that returns a Promise, what does TypeScript infer, and how would you explicitly annotate it?

2-5 years experience
  1. 1

    You're adding a new API client method fetchUser(id) that can accept either a string ID or a number ID and returns a User object. How would you write the function signature with proper overloads or union types?

  2. 2

    During a code review you notice a function that uses any for its parameters to avoid type errors, but the team wants stricter typing. How would you refactor the function to use generics while preserving its flexibility?

5-8 years experience
  1. 1

    Our front‑end library exposes a higher‑order component withLoading that wraps any component and injects loading props. How would you type annotate this HOC to preserve the wrapped component’s props and ensure correct inference for consumers?

  2. 2

    We have a performance‑critical data‑processing pipeline where functions are composed at runtime. What trade‑offs do you consider when deciding between explicit function type annotations versus relying on inference, especially regarding bundle size and compile‑time checking?

8+ years experience
  1. 1

    The company is migrating a large JavaScript codebase to TypeScript. How would you establish a strategy for annotating existing functions, balancing the need for immediate safety with the overhead of writing exhaustive signatures?

  2. 2

    Multiple teams share a common utilities package that includes many generic helper functions. What guidelines would you set for function type annotations to keep the API stable, avoid breaking changes, and support future extensions?

Follow-up Questions

  • What would happen if you omitted the return type annotation in the add function?
  • How does using a generic parameter affect the function’s call‑site type inference?
  • Can you describe a scenario where over‑annotating a function could cause maintenance issues?