Challenge - 5 Problems
InstanceType Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this code using InstanceType?
Consider the following TypeScript code using
InstanceType. What will be logged to the console?Typescript
class Animal { name: string; constructor(name: string) { this.name = name; } speak() { return `${this.name} makes a noise.`; } } type AnimalInstance = InstanceType<typeof Animal>; const pet: AnimalInstance = new Animal('Dog'); console.log(pet.speak());
Attempts:
2 left
💡 Hint
InstanceType extracts the instance type from a constructor function type.
✗ Incorrect
The
InstanceType utility type extracts the instance type that a constructor function returns. Here, AnimalInstance is the type of an instance of Animal. So, pet is an Animal instance and calling pet.speak() returns "Dog makes a noise.".🧠 Conceptual
intermediate1:30remaining
What does InstanceType do in TypeScript?
Choose the best description of what
InstanceType<T> does when T is a constructor type.Attempts:
2 left
💡 Hint
Think about what a constructor function returns when called with
new.✗ Incorrect
InstanceType<T> extracts the type of the object created by the constructor function type T. It does not create instances or convert types.❓ Predict Output
advanced2:00remaining
What is the type of variable 'obj' here?
Given this TypeScript code, what is the type of
obj?Typescript
class Person { constructor(public name: string, public age: number) {} } type PersonConstructor = typeof Person; type PersonInstance = InstanceType<PersonConstructor>; const obj: PersonInstance = { name: 'Alice', age: 30 };
Attempts:
2 left
💡 Hint
InstanceType extracts the instance type, which includes properties.
✗ Incorrect
The type
PersonInstance is the instance type of Person, which has name and age properties. The object literal matches this type, so it is valid.🔧 Debug
advanced1:30remaining
What error does this code produce?
Examine this TypeScript code using
InstanceType. What error will the compiler show?Typescript
type NotAConstructor = {
foo: string;
};
type Result = InstanceType<NotAConstructor>;
Attempts:
2 left
💡 Hint
InstanceType requires a constructor type as input.
✗ Incorrect
InstanceType expects a type that is a constructor function. Since NotAConstructor is just an object type without a constructor signature, the compiler errors.🧠 Conceptual
expert2:30remaining
Why use InstanceType instead of directly using a class type?
Which reason best explains why you might use
InstanceType<typeof SomeClass> instead of just using SomeClass as a type?Attempts:
2 left
💡 Hint
Think about generic programming and working with constructor types.
✗ Incorrect
InstanceType is useful when you have a constructor type (like typeof SomeClass) and want to get the instance type it creates, especially in generic or dynamic contexts where the class name might not be known directly.