0
0
Typescriptprogramming~20 mins

Explicit type annotations in Typescript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Explicit Type Annotations Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of explicit type annotation with union type
What is the output of the following TypeScript code?
Typescript
function formatInput(input: string | number): string {
  if (typeof input === 'number') {
    return `Number: ${input.toFixed(2)}`;
  } else {
    return `String: ${input.toUpperCase()}`;
  }
}

console.log(formatInput(3.14159));
console.log(formatInput('hello'));
ANumber: 3.14\nString: HELLO
B3.14\nHELLO
CNumber: 3.14159\nString: hello
DNumber: 3.1416\nString: HELLO
Attempts:
2 left
💡 Hint
Look at how the number is formatted with toFixed(2) and the string is converted to uppercase.
Predict Output
intermediate
1:30remaining
Value of variable with explicit tuple type
What is the value of the variable data after running this code?
Typescript
let data: [string, number];
data = ['age', 30];
console.log(data);
A['age', 30]
B[30, 'age']
C['age', '30']
D['age']
Attempts:
2 left
💡 Hint
Remember tuples have fixed order and types.
🔧 Debug
advanced
1:30remaining
Identify the error caused by wrong explicit type annotation
What error will this TypeScript code produce?
Typescript
let count: string = 10;
console.log(count);
ANo error, outputs 10
BSyntaxError: Unexpected number
CReferenceError: count is not defined
DType 'number' is not assignable to type 'string'.
Attempts:
2 left
💡 Hint
Check if the assigned value matches the declared type.
🧠 Conceptual
advanced
1:00remaining
Effect of explicit type annotation on function parameters
Which statement about explicit type annotations on function parameters is true?
AThey automatically convert arguments to the specified type at runtime.
BThey ensure the function only accepts arguments of the specified type, causing compile errors otherwise.
CThey are optional and have no effect on type checking.
DThey allow any type of argument but document the expected type.
Attempts:
2 left
💡 Hint
Think about how TypeScript enforces types during compilation.
Predict Output
expert
2:00remaining
Output of explicit type annotation with intersection types
What is the output of this TypeScript code?
Typescript
type A = { x: number };
type B = { y: string };

const obj: A & B = { x: 5, y: 'hello' };

console.log(obj.x + obj.y.length);
ANaN
BTypeError at runtime
C10
DSyntaxError
Attempts:
2 left
💡 Hint
Add the number x and the length of string y.