5

I want to use the fromObject key of HttpParamsOptions to cast an custom object into a params-object.

This works:

foo(): void {
   const testObject = {
     id: 123;
     name: 'test';
     someExample: 'test';
   }
   const httpParams = new HttpParams({ fromObject: testObject });
   ...
}

This doesn't work:

export interface SearchParams {
  id: number;
  name: string;
  someExample: string;
}

foo(testObject: SearchParams): void {
   const httpParams = new HttpParams({ fromObject: testObject });
   ...
}

fromObject does not work if I define the object type.

Error: TS2322: Type 'SearchParams' is not assignable to type '{ [param: string]: string | number | boolean | readonly (string | number | boolean)[]; }'.   Index signature is missing in type 'SearchParams'.

Any ideas how to solve this? I'm using Angular 12.

1
  • The constructor of HttpParams takes a parameter with an index signature. Commented Jun 18, 2021 at 19:20

1 Answer 1

6

The easyest way:

   const httpParams = new HttpParams({ fromObject: {...testObject} });

The error occur because your parameter type SearchParams doesn't match with the fromObject type that is:

    fromObject?: {
        [param: string]: string | number | boolean | ReadonlyArray<string | number | boolean>;
    }; 

Basically fromObject param accept any literal object.

So you can achieve the same result in some different ways. For example...

Declaring a literal object (as you did too):

    const testObject = {
      id: 123;
      name: 'test';
      someExample: 'test';
    }
    const httpParams = new HttpParams({ fromObject: testObject  });

Declaring an object copying from another using the spread operator:

    const myObject = { ...testObject };
    const httpParams = new HttpParams({ fromObject: myObject  });

Or casting as any type:

   const httpParams = new HttpParams({ fromObject: testObject as any });

From the typescript doc about the any type:

The any type is useful when you don’t want to write out a long type just to convince TypeScript that a particular line of code is okay.

Or changing the SearchParams interface to be compatible with the fromObject param type:

  export interface SearchParams {
    id: number;
    name: string;
    someExample: string;
    [param: string]: string | number;
  }
    
  foo(testObject: SearchParams): void {
    const httpParams = new HttpParams({ fromObject: testObject });
  }
Sign up to request clarification or add additional context in comments.

2 Comments

What about if I want to pass a complex object that have a parameter of object type. Can that be passed?
Agree that the spread operator resolves this issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.