Bird
Raised Fist0
Typescriptprogramming~10 mins

Default generic types in Typescript - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Default generic types
Define generic type with default
↓
Use generic without specifying type?
Yes→Use default type
No↓
Use generic with specified type
↓
Function or class runs with chosen type
This flow shows how a generic type with a default is defined and used either by specifying a type or by falling back to the default.
Execution Sample
Typescript
function wrap<T = string>(value?: T): (T | undefined)[] {
  return [value];
}

const a = wrap(123);
const b = wrap('hello');
const c = wrap();
This code defines a generic function with a default type string and calls it with different arguments to show default and explicit generic usage.
Execution Table
StepCallGeneric Type UsedValue PassedReturn Value
1wrap(123)number (inferred)123[123]
2wrap('hello')string (inferred)'hello'['hello']
3wrap()string (default)undefined[undefined]
💡 All calls complete; default generic type used when no argument is passed.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3
aundefined[123][123][123]
bundefinedundefined['hello']['hello']
cundefinedundefinedundefined[undefined]
Key Moments - 3 Insights
Why does wrap() use string as the generic type even though no argument is passed?
Because the generic type T has a default of string, when no type or argument is provided, TypeScript uses string as the default type (see execution_table step 3).
How does TypeScript decide the generic type when we call wrap(123)?
TypeScript infers the generic type from the argument's type, so T becomes number for wrap(123) (see execution_table step 1).
What happens if we explicitly specify a generic type when calling wrap?
The specified type overrides the default and inference, so the function uses that type for T.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what generic type is used in step 2 when calling wrap('hello')?
Astring (default)
Bstring (inferred)
Cnumber (default)
Dany
💡 Hint
Check the 'Generic Type Used' column in execution_table row for step 2.
At which step does the function use the default generic type?
AStep 3
BStep 2
CStep 1
DNone
💡 Hint
Look for 'string (default)' in the 'Generic Type Used' column in execution_table.
If we call wrap<boolean>(true), how would the generic type and return value appear?
AGeneric type: string, Return: ['true']
BGeneric type: any, Return: [true]
CGeneric type: boolean, Return: [true]
DGeneric type: boolean, Return: true
💡 Hint
Explicit generic types override defaults and inference; return is an array of the passed value.
Concept Snapshot
Default generic types let you set a fallback type for generics.
Syntax: function fn<T = DefaultType>(arg: T) { ... }
If no type is given or inferred, default is used.
Explicit types override default and inference.
Useful for flexible, safe code with sensible defaults.
Full Transcript
This lesson shows how default generic types work in TypeScript. We define a generic function with a default type string. When calling wrap with a number or string argument, TypeScript infers the generic type from the argument. When calling wrap with no argument, the default generic type string is used. Variables a, b, and c track the returned arrays. Key points include how inference and defaults interact, and how explicit generic types override both. The quizzes check understanding of these steps.

Practice

(1/5)
1.

What is the main purpose of default generic types in TypeScript?

easy
A. To provide a fallback type when no type argument is specified
B. To enforce a specific type always
C. To disable generics in a function
D. To convert types to strings automatically

Solution

  1. Step 1: Understand generic types

    Generic types allow functions or classes to work with any type specified by the user.
  2. Step 2: Role of default generic types

    Default generic types provide a fallback type if the user does not specify one explicitly.
  3. Final Answer:

    To provide a fallback type when no type argument is specified -> Option A
  4. Quick Check:

    Default generic types = fallback type [OK]
Hint: Defaults fill in missing generic types automatically [OK]
Common Mistakes:
  • Thinking default generics enforce a fixed type
  • Confusing default generics with type conversion
  • Believing default generics disable generics
2.

Which of the following is the correct syntax to set a default generic type T to string in a function?

function example<T = string>()
easy
A. function example<T extends string>()
B. function example<T: string>()
C. function example<T = string>()
D. function example<T? = string>()

Solution

  1. Step 1: Recall TypeScript generic syntax

    Default generic types use the equals sign (=) to assign a fallback type.
  2. Step 2: Analyze options

    function example<T = string>() uses <T = string> which is correct syntax for default generic types.
  3. Final Answer:

    function example<T = string>() -> Option C
  4. Quick Check:

    Default generic syntax uses = [OK]
Hint: Use = to assign default generic types [OK]
Common Mistakes:
  • Using colon (:) instead of equals (=)
  • Adding question mark (?) incorrectly
  • Confusing extends with default assignment
3.

What will be the output of the following TypeScript code?

function wrap<T = number>(value: T): T[] {
  return [value];
}

const result = wrap('hello');
console.log(result);
medium
A. ["number"]
B. ["hello"]
C. ["value"]
D. Type error

Solution

  1. Step 1: Understand default generic type usage

    The function wrap has a default generic type T = number, but the caller passes a string 'hello', so T becomes string.
  2. Step 2: Analyze function output

    The function returns an array containing the passed value, so it returns ["hello"].
  3. Final Answer:

    ["hello"] -> Option B
  4. Quick Check:

    Explicit type overrides default generic [OK]
Hint: Passed type overrides default generic type [OK]
Common Mistakes:
  • Assuming default generic always applies
  • Expecting a type error for different type
  • Confusing value with type name
4.

Identify the error in this TypeScript code using default generic types:

function identity<T = number>(arg: T): T {
  return arg.length;
}
medium
A. Property 'length' may not exist on type 'T'
B. No error, code is correct
C. Return type should be number, not T
D. Default generic type cannot be 'number'

Solution

  1. Step 1: Analyze the generic type and usage

    The generic type T defaults to number, but number does not have a length property.
  2. Step 2: Identify the error

    Accessing arg.length causes a TypeScript error because length may not exist on type T.
  3. Final Answer:

    Property 'length' may not exist on type 'T' -> Option A
  4. Quick Check:

    Accessing unknown properties on generic types causes errors [OK]
Hint: Check if generic type supports accessed properties [OK]
Common Mistakes:
  • Ignoring property existence on generic types
  • Thinking default generic restricts properties
  • Assuming no error if default is number
5.

Given this generic function with a default type, how can you call it to get an array of booleans?

function createArray<T = string>(length: number, value: T): T[] {
  return Array(length).fill(value);
}

Choose the correct call:

hard
A. createArray<boolean>(true, 3)
B. createArray(3, 'true')
C. createArray<number>(3, true)
D. createArray<boolean>(3, true)

Solution

  1. Step 1: Understand default generic and call signature

    The function defaults T to string, but to get an array of booleans, we must specify T = boolean.
  2. Step 2: Analyze options

    createArray<boolean>(3, true) explicitly sets T to boolean and passes true as value, which matches the type.
  3. Final Answer:

    createArray<boolean>(3, true) -> Option D
  4. Quick Check:

    Specify generic type to override default [OK]
Hint: Specify generic type to override default generic [OK]
Common Mistakes:
  • Relying on default generic without specifying type
  • Passing arguments in wrong order
  • Mismatching generic type and value type
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard