All quizzesEasy
Generic Basics — Series 2
Preview — 3 of 10 questions
javascript
function wrapInArray<T>(value: T): T[] {
return [value];
}
const nums = wrapInArray(5);
const strs = wrapInArray("hi");ABoth nums and strs are typed any[]
Bnums is typed number[], and strs is typed string[] — T is inferred separately for each call, based on that call's own argument
CBoth are typed (number | string)[], since T is treated as shared across all calls to wrapInArray
DCompile-time error — T[] isn't a valid generic return type
javascript
type Pair<A, B> = [A, B];
const coords: Pair<number, number> = [10, 20];
const entry: Pair<string, number> = ["age", 30];
const invalid: Pair<string, number> = [30, "age"];AAll three declarations compile fine
BType aliases can't be made generic — this is a compile-time error on the type Pair<A, B> declaration itself
Ccoords and entry compile fine; invalid compiles fine too, since tuple element order doesn't matter as long as the types are present
Dcoords and entry compile fine; invalid is a compile-time error, because its elements are swapped — 30 isn't assignable to the first position (string), and "age" isn't assignable to the second (number)
javascript
interface Wrapper<T> {
value: T;
unwrap(): T;
}
const numberWrapper: Wrapper<number> = {
value: 42,
unwrap() { return this.value; },
};ACompiles fine — Wrapper<number> instantiates the generic interface with T = number, requiring value: number and unwrap(): number, both of which the object literal satisfies
BCompile-time error — generic interfaces aren't allowed to include methods, only properties
CCompiles fine, but unwrap()'s return type is always any, regardless of T
DCompile-time error — this.value can't be referenced from inside the unwrap() method
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.