0
0
Typescriptprogramming~5 mins

InstanceType type in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the InstanceType type do in TypeScript?
<p><code>InstanceType</code> takes a class type and returns the type of instances created by that class.</p>
Click to reveal answer
beginner
How do you use <code>InstanceType</code> with a class named <code>Car</code>?

You write InstanceType<typeof Car> to get the type of an object created by new Car().

Click to reveal answer
beginner
Can InstanceType be used with interfaces or only classes?
<p><code>InstanceType</code> works only with class constructors, not interfaces.</p>
Click to reveal answer
intermediate
What happens if you use InstanceType on a type that is not a constructor?

TypeScript will give an error because InstanceType expects a constructor type.

Click to reveal answer
beginner
Why is InstanceType useful in TypeScript?
<p>It helps you get the instance type from a class type, so you can write safer and clearer code without repeating types.</p>
Click to reveal answer
What does InstanceType return?
AThe type of instances created by MyClass
BThe type of the MyClass constructor function
CThe static properties of MyClass
DThe interface implemented by MyClass
Can InstanceType be used with a function type?
AYes, always
BYes, but only with arrow functions
CNo, only with class constructors
DOnly if the function returns an object
What keyword do you use inside InstanceType to refer to a class type?
Anew
Btypeof
Cinstanceof
Dclass
If you have class Dog { bark() {} }, what type does InstanceType have?
AAn object with a <code>bark</code> method
BThe Dog class itself
CA function type
DUndefined
What error occurs if you use InstanceType on a non-constructor type?
ASyntax error
BNo error, it works fine
CRuntime error
DTypeScript error: Type is not a constructor
Explain how InstanceType helps when working with classes in TypeScript.
Think about how you get the type of an object created by a class.
You got /4 concepts.
    Describe a situation where using InstanceType would prevent a type error in your code.
    Consider when you want to refer to the type of an object created by a class without writing it yourself.
    You got /4 concepts.