Skip to content
FrontDepth, Home

Back to the topic

Practice: Generics

Answer first, then compare. Rate yourself honestly — it drives your weak-areas list.

3 predict-output · 4 open

Questions up to level

Shows questions up to the selected level.

No practice questions for this level yet.

  1. Predict the outputJunior

    describe is generic, but its body looks only at the value. The four calls pass different type arguments, explicit or inferred. The code type-checks under strict. What does it log?

    TypeScript
    function describe<T>(value: T): string {
      if (Array.isArray(value)) return "array of " + value.length;
      return typeof value;
    }
    
    console.log(describe<number>(42));
    console.log(describe<string | number>("42"));
    console.log(describe(["a", "b"]));
    console.log(describe<object | null>(null));
  2. Open questionJunior

    What problem do generics solve that any and unknown do not, and how does TypeScript decide what T is at a call?

    Think it through first

    Answer out loud or in your head as if you were in an interview, then reveal.

  3. Predict the outputMiddle

    parseJson<T> looks typed: the caller asks for a number, and the code type-checks under strict. The JSON text, though, holds a string. What does it log?

    TypeScript
    function parseJson<T>(text: string): T {
      return JSON.parse(text);
    }
    
    const count = parseJson<number>('"41"');
    const next = count + 1;
    
    console.log(typeof count);
    console.log(next);
    console.log(next === 42);
  4. Open questionMiddle

    Write a type-safe getProperty(obj, key). Why does it need two type parameters?

    Think it through first

    Answer out loud or in your head as if you were in an interview, then reveal.

  5. Open questionMiddle

    How do you tell that a type parameter is unnecessary, or worse, a disguised cast?

    Think it through first

    Answer out loud or in your head as if you were in an interview, then reveal.

  6. Predict the outputSenior

    Dog is assignable to Animal, and TypeScript accepts a Dog[] where an Animal[] is expected. The code type-checks under strict. What does it log?

    TypeScript
    type Animal = { name: string };
    type Dog = Animal & { bark(): string };
    
    const dogs: Dog[] = [{ name: "Rex", bark: () => "woof" }];
    const animals: Animal[] = dogs;
    animals.push({ name: "Tom" });
    
    console.log(dogs.length);
    console.log(dogs[1].name);
    console.log(typeof dogs[1].bark);
  7. Open questionSenior

    What do const type parameters and NoInfer change, and when would you use them?

    Think it through first

    Answer out loud or in your head as if you were in an interview, then reveal.