Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda Generic Functions in Practice | Working with Generics
Working with Interfaces and Generics in TypeScript

bookGeneric Functions in Practice

When you need to create utility functions that work with different data types while maintaining type safety, generic functions in TypeScript are the answer. A generic function lets you define a placeholder type variable, often called T, which stands for "type." You can use this type variable within the function's parameters and return type. This way, the function adapts to the type of data it receives, ensuring that the TypeScript compiler checks types correctly.

12345678
// Generic function to return the first element of an array function firstElement<T>(arr: T[]): T | undefined { return arr[0]; } // Usage examples: const num = firstElement([10, 20, 30]); // num: number | undefined const str = firstElement(["a", "b", "c"]); // str: string | undefined
copy

Generic functions make your utility code more flexible and reusable. By writing functions that can operate on any type, you avoid duplicating logic for each specific type you might encounter. This approach leads to code that is both safer and easier to maintain, since TypeScript enforces type correctness no matter what types you use with your generic function.

12345678
// Generic function to merge two objects of the same type function mergeObjects<T>(obj1: T, obj2: T): T { return { ...obj1, ...obj2 }; } // Usage example: const merged = mergeObjects({ name: "Alice" }, { age: 30 }); // merged: { name: string; age: number }
copy

TypeScript is often able to infer the type parameter for your generic function based on the arguments you provide. This means you rarely need to specify the type explicitly when calling a generic function. Instead, TypeScript analyzes the types of the arguments and fills in the generic parameter for you, keeping your code concise and easy to read.

question-icon

Fill in the blanks to complete a generic function that returns the last element of an array.

(arr: []): | undefined { return arr[arr.length - 1]; }
Depends on the array passed to the function. For example, lastElement([1, 2, 3]) returns 3.

Clique ou arraste solte itens e preencha os espaços

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 2. Capítulo 2

Pergunte à IA

expand

Pergunte à IA

ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

Awesome!

Completion rate improved to 9.09

bookGeneric Functions in Practice

Deslize para mostrar o menu

When you need to create utility functions that work with different data types while maintaining type safety, generic functions in TypeScript are the answer. A generic function lets you define a placeholder type variable, often called T, which stands for "type." You can use this type variable within the function's parameters and return type. This way, the function adapts to the type of data it receives, ensuring that the TypeScript compiler checks types correctly.

12345678
// Generic function to return the first element of an array function firstElement<T>(arr: T[]): T | undefined { return arr[0]; } // Usage examples: const num = firstElement([10, 20, 30]); // num: number | undefined const str = firstElement(["a", "b", "c"]); // str: string | undefined
copy

Generic functions make your utility code more flexible and reusable. By writing functions that can operate on any type, you avoid duplicating logic for each specific type you might encounter. This approach leads to code that is both safer and easier to maintain, since TypeScript enforces type correctness no matter what types you use with your generic function.

12345678
// Generic function to merge two objects of the same type function mergeObjects<T>(obj1: T, obj2: T): T { return { ...obj1, ...obj2 }; } // Usage example: const merged = mergeObjects({ name: "Alice" }, { age: 30 }); // merged: { name: string; age: number }
copy

TypeScript is often able to infer the type parameter for your generic function based on the arguments you provide. This means you rarely need to specify the type explicitly when calling a generic function. Instead, TypeScript analyzes the types of the arguments and fills in the generic parameter for you, keeping your code concise and easy to read.

question-icon

Fill in the blanks to complete a generic function that returns the last element of an array.

(arr: []): | undefined { return arr[arr.length - 1]; }
Depends on the array passed to the function. For example, lastElement([1, 2, 3]) returns 3.

Clique ou arraste solte itens e preencha os espaços

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 2. Capítulo 2
some-alt