Generic conditional constraints in Typescript - Mini Project: Build & Apply
describeInput with a type parameter T. The function should accept one parameter called input of type T. For now, just return the input as is.Define a generic function with and a parameter input of type T.
T to extend string | number so that describeInput only accepts strings or numbers.Use T extends string | number to restrict the generic type.
describeInput to a conditional type that returns string. Inside the function, use a typeof check on input to return `String input: ${input}` if input is a string, or `Number input: ${input}` if input is a number.Use typeof inside the function to check the input type and return the correct message.
describeInput with the string 'hello' and the number 42. Print both results using console.log.Use console.log to print the results of calling describeInput with 'hello' and 42.
Practice
What does a generic conditional constraint in TypeScript allow you to do?
For example, in function example(arg: T) {}, what is the main purpose?
Solution
Step 1: Understand generic conditional constraints
Generic conditional constraints let you choose a type based on a condition, likeT extends U ? X : Y.Step 2: Identify the purpose in the example
This controls the generic type to be eitherXorYdepending on whetherTextendsU, improving type safety.Final Answer:
Control the generic type based on a condition to improve type safety -> Option AQuick Check:
Generic conditional constraints = control type conditionally [OK]
- Confusing conditional constraints with runtime conditions
- Thinking it affects performance instead of types
- Assuming it disables type checking
Which of the following is the correct syntax for a generic conditional constraint in TypeScript?
function test<T>(arg: T extends string ? number : boolean) {}Solution
Step 1: Identify correct generic conditional syntax
The conditional type must be used in the argument type, not in the generic constraint part.Step 2: Check each option
function test<T>(arg: T extends string ? number : boolean) {} correctly places the conditional type in the argument type:arg: T extends string ? number : boolean.Final Answer:
function test<T>(arg: T extends string ? number : boolean) {} -> Option AQuick Check:
Conditional type goes in argument type, not generic constraint [OK]
- Putting conditional directly in generic constraint
- Using invalid syntax like 'where'
- Misplacing parentheses in conditional
What is the output of this TypeScript code?
type Result<T> = T extends number ? "Number" : "Other";
const a: Result<42> = "Number";
const b: Result<string> = "Other";
console.log(a, b);Solution
Step 1: Understand the conditional type Result<T>
IfTis a number,Result<T>is "Number", else "Other".Step 2: Apply to given values
Result<42>is "Number" because 42 is a number.Result<string>is "Other" because string is not a number.Final Answer:
Number Other -> Option BQuick Check:
Conditional type matches number = "Number", else "Other" [OK]
- Confusing value 42 with type number
- Assuming string extends number
- Mixing up output strings
Identify the error in this TypeScript code using generic conditional constraints:
function checkType<T>(value: T): T extends string ? number : boolean {
if (typeof value === "string") {
return value.length;
} else {
return true;
}
}Solution
Step 1: Analyze return type conditionality
The return type depends onT, but at runtime TypeScript cannot guarantee which type is returned.Step 2: Understand why error occurs
Returningvalue.length(number) ortrue(boolean) causes a type error because TypeScript can't confirm the return matches the conditional type without assertions.Final Answer:
Cannot return different types conditionally without type assertion -> Option DQuick Check:
Conditional return types need type assertions or overloads [OK]
- Assuming TypeScript infers conditional return types automatically
- Adding generic constraints unnecessarily
- Changing parameter types instead of fixing return
Given this TypeScript code, what is the type of result?
type ConditionalType<T> = T extends { id: number } ? string : number;
function processItem<T>(item: T): ConditionalType<T> {
if ("id" in item) {
return "Has ID" as ConditionalType<T>;
} else {
return 0 as ConditionalType<T>;
}
}
const result = processItem({ id: 123, name: "Test" });Solution
Step 1: Understand the conditional type ConditionalType<T>
IfThas anidproperty of type number, the type isstring, elsenumber.Step 2: Apply to the argument type
The argument{ id: 123, name: "Test" }has anidproperty of type number, soConditionalType<T>isstring.Final Answer:
string -> Option CQuick Check:
Object with id:number means ConditionalType = string [OK]
- Thinking result is number because of return 0
- Assuming union type without checking condition
- Ignoring the conditional type logic
Ready to prove it?
Pass the test and this pattern moves unknown
