Index

Typescript Generics

Topic

In Typescript there is a concept of a “Generic” VariableName I have used them before but I honestly don’t really understand what they are.

Conjecture

I believe that the concept of a generic reference to a general classes in typescript and can be extended or picked off of to create more specific types. For examples you could have a general type or a generic:

food {
	type
	color
	name
	parentPlant
}

Then you could extend the food type here to create a vegetable type which would just have the properties parentPlant and name.

Thus, the food is a generic type? That can be used to create a more specific vegetable type?

Research

Ok, I was totally wrong. A generic is when you write a function that can be “passed” a type. If a function takes a “type” argument, then it is “generic,” i.e. it supports multiple types and doesn’t explicitly state the type.

When you use a generic, you can just capture the type and use it to describe what a function expects without explicitly defining the type. This allows you to create more flexible functions and components in TypeScript while still maintaining some control and type safety.

For example you could create a generic class:

class GenericPermission {
	name: string
	module: ModuleType
	isAllowed: (action: string) => boolean;
} 

This isn’t a great example because ideally you would use the module type more in the class, but I do think it is technically valid.

You can continue with generic by specifying that the type passed has specific keys or properties for it to be a valid input to the function.

For example:

getProperty(obj: Type, key: Key) {
  return obj[key];
}

Thus, you can pass in two types, but the second type must be a key of the first type to be valid.

You can also set type defaults using extends and = as the arguments of a function like so:

create (element?:T): Container {
	// returns a Container wrapping the passed element, or a div by default
}

In this way the type parameter falls back to HTMLDivElement when you call create() with no argument, because there is nothing for TypeScript to infer the type from. Worth being precise that this is a type-level default — it fills in the missing type argument at compile time. It is not a runtime fallback, so passing null won’t trigger it.

Final Summary

Generics allow you to define functions and components with more flexible types. Instead of always explicitly defining every argument and return type you can use a type to allow the same function to service multiple types and just pass the type definition in or have the TS compiler infer it.