0
0
Typescriptprogramming~5 mins

Generic interface declaration in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a generic interface in TypeScript?
A generic interface is a way to define an interface with a placeholder type that can be specified later, allowing the interface to work with different data types while keeping type safety.
Click to reveal answer
beginner
How do you declare a generic interface with one type parameter named <T>?
You write: <br>interface MyInterface<T> {<br> value: T;<br>}<br>This means the interface has a property 'value' of type T, which will be specified when used.
Click to reveal answer
beginner
Why use generic interfaces instead of fixed types?
Generic interfaces let you write flexible and reusable code that works with many types without losing the benefits of type checking.
Click to reveal answer
beginner
Example: What does this interface mean?<br>interface Box<T> { content: T; }
It means 'Box' can hold any type of content. When you use it, you specify the type, like Box<string> for a box holding strings or Box<number> for numbers.
Click to reveal answer
intermediate
Can a generic interface have multiple type parameters? How?
Yes. You separate them with commas inside the angle brackets. For example:<br>interface Pair<T, U> { first: T; second: U; }
Click to reveal answer
How do you declare a generic interface named 'Container' with one type parameter 'T'?
Ainterface Container { item: T; }
Binterface Container<T> { item: any; }
Cinterface Container<T> { item: T; }
Dinterface Container<T> { item: string; }
What is the benefit of using a generic interface?
AIt allows the interface to work with any type while keeping type safety.
BIt makes the interface only work with strings.
CIt disables type checking.
DIt makes the interface slower.
Which syntax correctly declares a generic interface with two type parameters?
Ainterface Pair<T; U> { first: T; second: U; }
Binterface Pair<T, U> { first: T; second: U; }
Cinterface Pair<T U> { first: T; second: U; }
Dinterface Pair { first: T; second: U; }
If you have interface Box<T> { content: T; }, what is the type of 'content' in let box: Box<number>;?
Anumber
Bstring
Cany
DT
Can you use a generic interface without specifying the type parameter?
AYes, it defaults to 'any'.
BNo, generic interfaces cannot be used.
CYes, it defaults to 'string'.
DNo, you must specify the type parameter.
Explain what a generic interface is and why it is useful in TypeScript.
Think about how you can write one interface that works with many types.
You got /4 concepts.
    Write a simple generic interface named 'Result' that holds a value of any type and a boolean indicating success.
    Use angle brackets <> to declare the generic type.
    You got /4 concepts.