Hello and welcome! Today, we're exploring practical data manipulation techniques in TypeScript. We'll utilize TypeScript arrays to represent our data streams and perform projection, filtering, and aggregation operations. Our operations will be neatly encapsulated within a TypeScript class for clean, structured code with built-in type annotations.
Data manipulation is akin to sculpting, but for data. We shape our dataset to derive the desired structure. TypeScript arrays with type annotations give us clarity and safety. Our manipulation operations will be part of a TypeScript class. Let's prepare our toolbox:
Our first stop is data projection, akin to capturing a photo of our desired features. Imagine we have data about people. If we're only interested in names and ages, we can project our data to focus solely on these details. We'll extend our DataStream class with a projectData method, leveraging TypeScript's type system:
The projectData method in the DataStream class creates a new DataStream instance that contains only the specified keys from each element in the original data array. It accepts an array of keys as input. The method iterates over each element in the data and constructs a new object, newObj, for each element. Using Partial<DataElement> for newObj allows these objects to only include some properties of DataElement, making them optional. In the method, the forEach loop assigns the value of each specified key to newObj, ensuring that only desired fields are retained. The newly constructed projectedData, which consists of partially constructed DataElement objects, is then used to instantiate and return a new DataStream.
