TypeScript - Advanced Types, Interfaces & Generics
Cards in this deck
(23 cards)Preview terms and definitions before starting your study session.
T) to make the function work with different types while preserving type safety.function identity<T>(arg: T): T {
return arg;
}
let output1 = identity<string>("myString"); // type of output1 is string
let output2 = identity<number>(100); // type of output2 is numberinterface Box<T> {
value: T;
}
let stringBox: Box<string> = { value: "hello" };
let numberBox: Box<number> = { value: 123 };class GenericNumber<T> {
zeroValue: T;
add: (x: T, y: T) => T;
constructor(zeroValue: T, addFunction: (x: T, y: T) => T) {
this.zeroValue = zeroValue;
this.add = addFunction;
}
}
let myGenericNumber = new GenericNumber<number>(0, (x, y) => x + y);
console.log(myGenericNumber.add(5, 10)); // 15interface Lengthwise {
length: number;
}
function loggingIdentity<T extends Lengthwise>(arg: T): T {
console.log(arg.length); // Now we know 'arg' has a .length property
return arg;
}
loggingIdentity({ length: 10, value: 3 }); // OK
// loggingIdentity(3); // Error: Argument of type 'number' is not assignable to parameter of type 'Lengthwise'.AND operator for types.type Draggable = { drag: () => void };
type Resizable = { resize: () => void };
type UIWidget = Draggable & Resizable;
let widget: UIWidget = {
drag: () => console.log('Dragging...'),
resize: () => console.log('Resizing...')
};OR operator for types. If a value has a union type, you can only access members that are common to all types in the union, unless you use type guards.type StringOrNumber = string | number;
function printId(id: StringOrNumber) {
console.log(id);
}
printId(101); // OK
printId("abc"); // OKRelated Flashcard Sets
Explore similar study materials created by the community
Korean TOPIK I - Essential Vocabulary & Grammar (Levels 1-2)
Master essential Korean vocabulary and grammar for the TOPIK I exam! This deck covers Hangeul, greetings, numbers, basic verbs, particles, and sentence structures to build your foundational Korean fluency.
Organic Chemistry Mechanisms - SN1/SN2 & E1/E2 Reactions
Master the core of organic reactions! Unravel the intricate electron-pushing mechanisms of SN1, SN2, E1, and E2 reactions, understanding their kinetics, stereochemistry, and the factors that dictate product outcomes.
Cisco CCNA (200-301) - Enterprise Networking & IP Services
Master enterprise networking and IP services for the Cisco CCNA (200-301) exam with this high-yield flashcard deck. Dive deep into TCP/IP, subnetting, routing, VLANs, STP, NAT, and essential Cisco IOS commands to solidify your certification knowledge.
Stanford CS106A - Programming Methodology (Java Basics)
Master Java programming fundamentals with this comprehensive flashcard deck, covering variables, control structures, methods, arrays, and object-oriented basics essential for CS106A success. Elevate your coding skills and ace your programming journey!