10. What are generic types (generics)?

Generics in TypeScript is a mechanism allowing developer to create general types and functions, which may work with different types passed as kind of an argument. It allows to create more elastic and type-safe code.

const firstElement = function <T>(arr: T[]): T | undefined { return arr[0]; } const num: number | undefined = firstElement([1, 2]); const string1: string | undefined = firstElement([1, 2]); // Type 'number' is not assignable to type 'string' const string2: string | undefined = firstElement(["a", "b"]);

Generics can be used also in classes or interfaces declarations.

Generic types can extend other types or accept default values:

interface RandomInterface { abc: string } const firstElement = function <T extends RandomInterface>(arr: T[]): T | undefined { return arr[0]; } //default type const lastElement = function <T = RandomInterface>(arr?: T[]): T | undefined { return ...; } const last = lastElement(); // Assumes last is of type RandomInterface const first = firstElement([{value: "val"}]); // Object literal may only specify known properties, and 'value' does not exist in type 'RandomInterface' const anotherFirst = firstElement([{abc: "ABC", value: "val"}]); // OK

For more information, you can check here.

devFlipCards 2024

Do you accept cookies?

Cookies are small amounts of data saved locally on you device, which helps our website - it saves your settings like theme or language. It helps in adjusting ads and in traffic analysis. By using this site, you consent cookies usage.