Middle+
How are things with TypeScript? Have you used generics, utility types, TypeGuard?
sobes.tech AI
Answer from AI
In working with TypeScript, I actively used generics, utility types, and TypeGuards.
- Generics allow creating reusable components with types specified at usage. For example:
function identity<T>(arg: T): T {
return arg;
}
-
Utility types (such as
Partial<T>,Pick<T, K>,Omit<T, K>) help create new types based on existing ones, simplifying type management and increasing safety. -
TypeGuard — these are functions that check the type of a value at runtime and help the compiler narrow down the type. For example:
type Fish = { swim: () => void };
type Bird = { fly: () => void };
function isFish(pet: Fish | Bird): pet is Fish {
return (pet as Fish).swim !== undefined;
}
function move(pet: Fish | Bird) {
if (isFish(pet)) {
pet.swim();
} else {
pet.fly();
}
}
Using these features of TypeScript significantly improves code quality and reduces errors.