Typescript Generics
Topic
In Typescript there is a concept of a “Generic” VariableName
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) => 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 {
return div: Container
} In this way you make it so that the HTML element defaults to being a dev if it doesn’t have a type or null is passed to the function.
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 complier infer it.