Skip to the solution
MediumFrontend10 min read

What are generic constraints?

1.1k views

The problem

Question presented to candidate: "What is a generic constraint? Write a function that only accepts things with a length, and a getProperty(obj, key) that rejects keys the object does not have."

What a strong answer should cover:

  • T extends X sets an upper bound: T can be X or any subtype of it, and inside the function you may use the members X guarantees
  • Without a constraint, x.length on a T is an error; with T extends { length: number } it is allowed, and the caller type (string, array) is still preserved in the return
  • Constraints can refer to other type parameters: K extends keyof T, returning T[K]
  • Why a constraint beats a plain parameter type: (x: HasId) => HasId forgets extra fields, <T extends HasId>(x: T) => T keeps them
  • The classic error: returning { id: 0 } as T fails because T "could be instantiated with a different subtype of constraint"
  • Variants: T extends object, unions (T extends string | number), intersections for several requirements, constructor types (new () => T)

Code / implementation expected: Yes β€” a longest or getProperty with a constraint, and the error it prevents.

  • generics
  • constraints

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read Β· 11 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

TypeScriptConstraints: length, K extends keyof T and unions
TypeScriptKeeping the caller type and the different subtype error

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 17 of 81 in TypeScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextMedium

What are assertion functions (asserts)?

Continue