After declaring the variable and before assigning it, use : to specify the types
Defining Objects
Union Type
Defining functions
Defining arrow functions
The above methods work when you are defining the function, when you need to just declare the function in a interface or type, use the following syntax :
Defining object parameters
Types Vs Interfaces
Extending Types
Extending Interfaces
Adding new fields to an existing interface
Adding new fields / properties does not work in type
Summary:
Interfaces and types can mostly be used interchangeably.
Interface can be implemented by classes (supports class method)
Interfaces can extend each other
Types can do unions and intersections
Interfaces are used for objects where as types can be used for anything.
Defining types for Actions in Reducer hook
Type Assertions Vs Type annotations
The as keyword is used for type assertions. It tells TypeScript that you're certain about the type of a value, even if TypeScript's type inference might suggest a different type.
The : syntax is used for type annotations. Type annotations explicitly specify the type of a variable or a function parameter. They're helpful when you want to provide type information that TypeScript cannot infer automatically.
In most cases, TypeScript's type inference is sufficient, and you don't need to explicitly provide type annotations.
Generics
Consider this example where you have the same function for two different data types:
You can use generics to write a single function that works for both data types:
In this example, <T> is a type parameter that represents the type that the function will work with. When calling the function, you can specify the type you want to use, making the code more flexible and type-safe.
Generics with Classes
In this example, the Stack class has a type parameter <T>, which allows it to work with different data types while maintaining type safety.
Generics with Interfaces
Here, the KeyValuePair interface has two type parameters, <T> and <U>, representing the types of the key and value properties, respectively
Partials
Used to get some elements from a type. Essentially make all the types optional so that we have the flexibility to choose what we want to send.
Usage
Pick
Similar to Partial we have Pick which allows you to construct a new type by selecting properties (Keys) from an existing type (Type).