Pipe transform use reduce for array of object - arrays

this is my Interface file :
export interface ListCount {
centre?: string;
cause?: string;
totalTime?: number;
}
I am trying to make reduce to array of objects with pipe transform :
export class SumPipe implements PipeTransform {
transform(items: ListCount[], attr: string): number {
return items.reduce((a, b) => a + b[attr], 0);
}
}
and in compent HTML I looking to make sum of totalTime
{{ (delayCount$ | async) | sum:'totalTime'}}
But I have this error :
error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'ListCount'.
Then I change the param attr: string to attr: keyof ListCount
and still have this error :
error TS2365: Operator '+' cannot be applied to types 'number' and 'string | number'.
and
error TS2532: Object is possibly 'undefined'.
Any help please

I would suggest the following:
restrict attr to point to numeric properties
take into account that properties can be optional. Use zero for those.
alternatively filter out missing (undefined) values.
export interface ListCount {
centre?: string;
cause?: string;
totalTime?: number;
otherTime?: number;
}
type NumericKeys<T> = {
[P in keyof T]: T[P] extends number ? P : never;
}[keyof T];
type NumericListCountKey = NumericKeys<Required<ListCount>>;
class SumPipe {
transform(items: ListCount[], attr: NumericListCountKey): number {
const elemes = items.map(elem => elem[attr]);
return elemes.reduce((prev: number, currentVal) => prev + (currentVal ? currentVal : 0), 0);
}
}
// alternatively, with filter
class SumPipe2 {
static isNumber(n: number | undefined): n is number {
return n != null;
}
transform(items: ListCount[], attr: NumericListCountKey): number {
const elems = items.map(elem => elem[attr])
.filter(SumPipe2.isNumber);
return elems.reduce((prev: number, currentVal) => prev + currentVal, 0);
}
}
Playground link

Ok, so your code compiles without issues and works. Here is a working stackblitz. If it fails on your local environment, perhaps try checking TS version, try restarting the Angular CLI, look for other issues or at least provided information on which line exactly the error is thrown.
There are a few issues with your code though.
As others have noted, passing any attr to the pipe and using the bracket notation to get the property value makes no sense. Only object accepted by the pipe is ListCount[], so it HAVE to be totalTime that gets summed as it's the only numeric property. It would make sense if you made more generic pipe that would accept any[] though.
Your pipe is not guarded for your use-case. totalTime is an optional property, meaning that if any item doesn't have totalTime defined (which it can, according to your interface) the pipe will return NaN. Not sure if that's the desired behavior.

According to this article, reduce() has an optional index, which points to the current index in the array. Knowing this, I'd opt for the following solution, leaving out attr entirely.
return items.reduce((a, b, index) => a + b[index].totalTime, 0);

Related

How to trim all string properties of a class instance?

I have an instance of some class.
Let's say this class is Person:
class Person {
name?: string | null;
age?: number | null;
friends!: Person[];
isLucky: boolean;
}
How to iterate over this instance and call trim() method on all properties that are strings? Because if I'm trying to do this:
(Object.keys(person) as (keyof typeof person)[]).forEach((key) => {
const value = person[key];
if (typeof value === 'string') {
person[key] = value.trim();
}
});
My friend Typescript shows this error:
Type 'string' is not assignable to type 'person[keyof person]'.
I want to write an all around method suitable for instances of different classes with many different properties.
Is there a way to achieve this in Typescript? May be some typing magic?
I would do it this way. Just cast it to any.
(Object.keys(person) as (keyof typeof person)[]).forEach((key) => {
const value = person[key];
if (typeof value === 'string') {
(person as any)[key] = value.trim();
}
});
TypeScript isn't able to determine if the key is associated with a specific typed key from Person, only that it's one of them. So you'll get a type of never when accessing person[key] without any other specific checks on key.
The quickest answer is to narrow your key:
(Object.keys(person) as (keyof typeof person)[]).forEach((key) => {
const value = person[key];
if (key === 'name' && typeof value === 'string') {
person[key] = value.trim();
}
});
Alternatively you could do the .trim() in your class constructor and avoid this entirely, but it's unclear what the context is for your issue.
Generally I avoid doing a forEach to map an Object and might favor Object.from over an Object.entries with a .map() or reconsider the data structure entirely depending on what your actual use case might be.

Types of property 'type' are incompatible. Problem with Typescript union types

Background
I am building a react site with some reusable generic UI components. Our backend service will return some responses with the data conforming to an abstract type.
For example
interface TypeAServerResponse {
somefield: string,
otherfield: string,
}
interface TypeBServerResponse {
somefield: string,
}
type TypeServerResponseUnion = TypeAServerResponse | TypeBServerResponse;
Both of the server response types contain somefield, and we would like to display that in the reused UI component. So we union them and tell the component to expect TypeServerResponseUnion.
However, in some occasions, we would also want to use otherfield, so we need to tell TypeScript to we are discriminating the union type. Without changing the backend to return a string literal, we are extending the ServerResponse types to contain a type string literal.
interface TypeA extends TypeAServerResponse{
$type: 'a',
}
interface TypeB extends TypeBServerResponse{
$type: 'b',
}
type TypeUnion = TypeA | TypeB; //or
type TypeUnion = TypeServerResponseUnion extends {
$type: 'a'|'b',
}
Now we can check on $type field in our UI component to discriminate the union and get otherfield when possible.
The problem
We now have some method to fetch the data from the server that returns TypeServerResponseUnion, and we want to parse it to TypeUnion before providing it to the UI layer.
// could be ajax.get, could be axios
const serverGet = () : TypeServerResponseUnion => {
return {somefield: 'something'}
}
const parse = () : TypeUnion => {
const response : TypeServerResponseUnion = serverGet();
// do something here to add the $item field and return it
}
We have two use cases
We know which concrete type we are asking for, so we can just provide the $type to the function. This has some problems I don't know how to deal with.
We don't know which concrete type we are asking for, we only know we are asking for a same type as we already have, this is the part where I am struggling with.
So I have the parse function as such:
const get = (original: TypeUnion) => {
const response = serverGet();
const parsedResponse: TypeUnion = {...response, $type: original.$type}
return parsedResponse
}
It complains with error:
Type '{ $type: "a" | "b"; somefield: string; otherfield: string; } | { $type: "a" | "b"; somefield: string; }' is not assignable to type 'TypeUnion'.
Type '{ $type: "a" | "b"; somefield: string; }' is not assignable to type 'TypeUnion'.
Type '{ $type: "a" | "b"; somefield: string; }' is not assignable to type 'TypeB'.
Types of property '$type' are incompatible.
Type '"a" | "b"' is not assignable to type '"b"'.
Type '"a"' is not assignable to type '"b"'.(2322)
So I want to know what is the best way to do typing for those types to solve this use case we are facing.
Extension
I also want to discuss this related problem with typescript.
If I change the get function to the following:
const get = (original: TypeUnion) => {
const response = serverGet();
const parsedResponse: TypeUnion = {} as TypeUnion;
parsedResponse.$type = original.$type
return parsedResponse
The error goes away, but of course because we are doing wrong type casting so it is not safe.
The question is why can we assign original.$type to TypeUnion.$type, where previously
const parsedResponse: TypeUnion = {...response, $type: original.$type}
we are assigning original.$type to $type during construction time does not work.
Playground with code
The reason for the type error is because you do not know if original and response are of the same type. Since they are both unions one could be of type "A" and the other of type "B". This might be be the true in the real implementation but it's not true in terms of the types.
We know which concrete type we are asking for, so we can just provide the $type to the function. This has some problems I don't know how to deal with.
This sorta seems like an anti pattern to me. If you know what type is coming from the backend then serverGet should not return a union but have the return type TypeAServerResponse or TypeBServerResponse
We don't know which concrete type we are asking for, we only know we are asking for a same type as we already have, this is the part where I am struggling with.
For this it is probably best to write a helper parse function (as you already did) but have but parse based on the data and not a value that is passed in.
const getPraseValueFromSErver: ()=>TypeUnion= () => {
const res = serverGet();
if("otherfield" in res){
// we know we have type A since otherfield exsists in the data
return { $itemType: "a", ...res}
} else {
// we know we have type B
return { $itemType: "b", ...res}
}
}
See full playground here

Conditional Type Checking based on function parameter

Im writing a custom Hook that can take either one or two strings, or an object with more granular parameters. I wanted to add a conditional type check to check for a type of that param and do some logic based on it. Here are the relevant snippets:
// The hook itself
const [error, loading, data] = useFirestore('posts', 'test'); // in a string version
const [error, loading, data] = useFirestore({...someProps}); // in a object version version
// The types that i defined for them
type queryType<T> = T extends string ? string : documentQueryType;
type docType<T> = T extends string ? string : never;
type documentQueryType = {
collection: string;
query: string[] | string[][];
limit: number;
orderBy: string; // todo limit this to be only special words
order: string; // todo same as above
startAt: number;
endAt: number;
};
// The function that is in the question
export const useFirestore = <T>(query: queryType<T>, doc?: docType<T>) => {...rest of the function
How would I make the last snippet work so when passed an object it sets doc to never, and when passed a string sets the doc to string?
This can be partially achieved with conditional types, but it may not be 100% type-safe. Since doc is optional, it will not be required when the query is a string, and will still allow undefined when query is an object.
However, if these two scenarios are not an issue, this can be achieved with conditional types:
// Simplified type
type DocumentQueryType = {
collection: string;
};
// The two types of queries that are accepted
type QueryTypes = string | DocumentQueryType;
// Given the query type, infer the doc type
type InferDocType<QueryType> = QueryType extends string ? string : never;
const useFirestore = <QueryType extends QueryTypes>(query: QueryType, doc?: InferDocType<QueryType>) => { }
// Valid Examples
useFirestore('posts', 'test');
useFirestore({ collection: "" });
// Valid Examples (may not want these?)
useFirestore('posts');
useFirestore({ collection: "" }, undefined);
// Invalid Examples
useFirestore({ collection: "" }, "test");
// Argument of type '"test"' is not assignable to parameter of type 'undefined'.(2345)
useFirestore('posts', null);
// Argument of type 'null' is not assignable to parameter of type 'string | undefined'.(2345)

How to set function's param as a key from interface

I have interface and object which represents this interface:
MyInterface {
variableOne: string;
variableTwo: boolean;
variableThree: boolean;
...
}
Also I have function toggleFunction(x) which gets a key and toggles it in my object.
Which type do I need to set in param x in my toggle function to use it for toggle all boolean key in my object?
For example I need something like: toggleFunction(x: TYPE?)
Use keyof.
function toggleFunction(x: keyof MyInterface): void {
// ...
}
You can use a conditional mapped type that I usually call KeysMatching:
type KeysMatching<T, V> = { [K in keyof T]: T[K] extends V ? K : never }[keyof T];
And then toggleFunction() can be defined like this:
declare const o: MyInterface; // or wherever it comes from
function toggleFunction(x: KeysMatching<MyInterface, boolean>) {
o[x] = !o[x];
}
toggleFunction("variableTwo"); // okay
toggleFunction("variableThree"); // okay
toggleFunction("variableOne"); // error!
Hope that helps; good luck!
Link to code

Union Types expecting other type when passed as props to component?

I'm using Typescript with React.
I am retrieving data from an API that returns two type: VirtualMachine or Disk. The backend takes responsibility for distinguishing the resource type and returns the type of both depending on the results of the query:
requestMoreInfo: (resourceType: string, resourceId: number): AppThunkAction<ResourceActions> => (dispatch, getState) => {
let fetchResourceInfo = fetch('http://localhost:5004/GetResourceTypeInformation/' + resourceType + '/' + resourceId, {
method: 'GET'
})
I've declared a union type for my Redux state:
export interface ResourceState {
currentResourceInformation?: VirtualMachineInformation | DiskInformation;
}
and I am subsequently converting the response to the type determined by the resource type passed into the function and dispatching an action to update my components state. THIS IS WHERE I THINK I'M GOING WRONG.
if (resourceType == "Virtual Machine") {
var vmResponse = response.json() as VirtualMachineInformation;
dispatch({
type: 'RECEIVE_RESOURCE_INFO',
resourceInfo: vmResponse
});
}
else if (resourceType == "Disk") {
var diskResponse = response.json() as DiskInformation;
dispatch({
type: 'RECEIVE_RESOURCE_INFO',
resourceInfo: diskResponse
});
}
TypeScript appears to be happy with this. However, I am then trying to render a child component and passing this update state as a prop:
private requestResourceInformation = (resourceType: string, resourceId: number) => {
this.props.requestMoreInfo(resourceType, resourceId);
if (resourceType == "Virtual Machine") {
return <VirtualMachineResource virtualMachine={this.props.currentResourceInformation} />
}
}
This just maps a table with the data.
However, I'm retrieving the error:
Type 'VirtualMachineInformation | DiskInformation | undefined' is not assignable to type 'VirtualMachineInformation | undefined'.
Type 'DiskInformation' is not assignable to type 'VirtualMachineInformation | undefined'.
Type 'DiskInformation' is not assignable to type 'VirtualMachineInformation'.
Property 'azureVmId' is missing in type 'DiskInformation
I believe this is because TypeScript still considers the value as the union type and the expected value is present in VirtualMachine type but no present in the Disk type.
Where am I going wrong with this? Is there an explicit way to declare the specific type of the union after retrieving the data?
The virtualMachine property doesn't accept the DiskInformation interface as a value - and that is your problem. TypeScript compiler doesn't know what's the exact type of the value at the compile time so the type is guessed to be one among those three: VirtualMachineInformation, DiskInformation, undefined
As I wrote in the comments section - you can use (at least) three solutions to solve your problem:
use type assertions - https://www.typescriptlang.org/docs/handbook/basic-types.html#type-assertions - you can not use <Type>value syntax in tsx files
return <SomeComponent prop={value as Type}></SomeComponent>
use type guards https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards
if ([check if type of the value is the Type]) {
return [something else]
}
[TypeScript knows that the value IS NOT an instance of the Type here]
return <SomeComponent prop={value}></SomeComponent>
use overloads - http://www.typescriptlang.org/docs/handbook/functions.html#overloads
class X {
private y(x: "abc"): "cda";
private y(x: "cda"): "abc";
private y(x: string): string {
[method logic]
}
}

Resources