Types of property 'observers' are incompatible. Why? - typing

I'm trying to make a BehaviorSubject that will accept only values of the AvailableLanguages enum, but the compiler doesn't agree with my code for some reason.
Can you tell me why?
I'm using Angular 12.2.10.
Here is the service:
import { Injectable } from '#angular/core';
import { BehaviorSubject } from 'rxjs';
export enum AvailableLanguages {
EN = "en-US",
IT = "it-IT"
}
#Injectable({
providedIn: 'root'
})
export class UserService {
_selectedLanguage$: BehaviorSubject<AvailableLanguages> = new BehaviorSubject(AvailableLanguages.EN);
constructor() { }
}
Here is the compiler's error:
Error: src/app/services/user.service.ts:15:3 - error TS2322: Type 'BehaviorSubject<AvailableLanguages.EN>' is not assignable to type 'BehaviorSubject<AvailableLanguages>'.
Types of property 'observers' are incompatible.
Type 'Observer<AvailableLanguages.EN>[]' is not assignable to type 'Observer<AvailableLanguages>[]'.
Type 'Observer<AvailableLanguages.EN>' is not assignable to type 'Observer<AvailableLanguages>'.
Type 'AvailableLanguages' is not assignable to type 'AvailableLanguages.EN'.
15 _selectedLanguage$: BehaviorSubject<AvailableLanguages> = new BehaviorSubject(AvailableLanguages.EN);
~~~~~~~~~~~~~~~~~~
× Failed to compile.

Hmm, probably because you are using strict in your tsconfig.json?
Not an issue as per se, though. You just need to make sure your types are "aligned".
So, your declaration:
_selectedLanguage$: BehaviorSubject<AvailableLanguages> = new BehaviorSubject(AvailableLanguages.EN);
Should be:
_selectedLanguage$: BehaviorSubject<AvailableLanguages> = new BehaviorSubject<AvailableLanguages>(AvailableLanguages.EN);
Or simply let TSC to infer the proper type:
_selectedLanguage$ = new BehaviorSubject<AvailableLanguages>(AvailableLanguages.EN);

Related

Receiving 'useState', which lacks return-type annotation, implicitly has an 'any' return type although type specified

I am receiving a Typescript error 'useState', which lacks return-type annotation, implicitly has an 'any' return type error although I have specified the type specifically, based on the best examples I can find. The applicable lines of my code are as follows:
interface IBDMRecord {
businessDevelopmentResourceId: number;
referenceName: string;
}
class ManagePreSalesBDMsApp extends React.Component<IAppProps, IAppState> {
static defaultProps: IAppProps = {
baseUrl: (window as any).SERVER_BASE_URL,
systemVersion: (window as any).SYSTEM_VERSION
}
const [data, setData] = useState<IBDMRecord[]>([]);
Visual Studio Code shows this as the problem:
Typescript v4.4.4 is installed. React v17.0.2 is installed. Any guidance would be greatly appreciated.
Update: I refactored to lambda function syntax and all is well.

How do you set types on getting Object.keys on JSON file in TypeScript?

I am trying to access an object from a JSON file and the error I am getting:
Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{...}'. ts(7053)
JSON file:
"networks": {
"5777": {
"event": {},
"links": {},
"address": "string",
"transactionHash": "string"
}
}
The value 5777 will be changed from time to time. So I am trying to access the value, which gives me an error.
Snippet from TS file:
import { abi, networks } from '../build/contracts/Example.json';
import Web3 from 'web3';
let networkId: any = Object.keys(networks)[0]; // 5777
new web3.eth.Contract(abi, networks[networkId].address); // causing error
You can cast it manually
let networkId = Object.keys(networks)[0] as keyof typeof networks; // 5777
Firstly i upvoted the #ABOS answer, and in enhancement and as a detailed have mentioned following source code for contract data creation using abi
import Web3 from 'web3'
import ElectionCommission, { networks as ecNetworks} from "./truffle_abis/ElectionCommission.json";
let networkId = Object.keys(ecNetworks)[0] as keyof typeof ecNetworks;
let ecCommissionData = new web3.eth.Contract(ElectionCommission.abi as any, ecNetworks[networkId].address);
Hope this would help manyones.

Type 'Observable<any>' is not assignable to type 'Observable<T>'

I have the following code
import {HttpClient} from '#ngular/common/http';
private httpClient: HttpClient;
do_request(method: string,
url: string,
headers?: HttpHeaders,
content?: string,
contentType?: string): Observable<MyResponse>{
let options = {
observe: 'response' as 'response',
responseType: 'text' as 'text',
headers: headers,
body: content:
}
return this.httpClient.request(method, url, options)
.map(res=> new MyResponse(res.status, res.body))
.catch(err=>Observable.throw(new MyResponse(err.status)));
}
This code is giving me the following error
error TS2322: Type 'Observable' is not assignable to type 'Observable'. Property 'source' is protected but type 'Observable' is not a class derived from 'Observable'
I'm using Rxjs 5.4.3, Angular 4.4.3 and TypeScript 2.5.3.
I've found several possible error sources and tried the suggested solutions with no luck:
Typescript version(I downgraded to 2.3 with similar results)
Importing a package that also has a dependency on rxjs using npm link (I installed it locally, with same result).
I will appreciate any suggestion on how to fix this issue.
Based on your comment, I think you should be explicit in your typings, hence, import Observable and declare the types:
return this.httpClient.request(method, url, options)
.map((res): MyResponse => new MyResponse(res.status, res.body))
.catch((err):Observable<MyResponse> => Observable.throw<MyResponse>(new MyResponse(err.status)));
The important part is that the throw (as well as from and other operators) can be typed and the syntax is `Observable.operator(operands...)

Pass array to async library eachSeries - expects 'Dictionary<{}>'

I have the following TypeScript code:
const allDescribeBlocks: Array<ITestSuite> = suman.allDescribeBlocks;
async.eachSeries(allDescribeBlocks, function (block: ITestSuite, cb: Function) {
//....
}, cb);
this will transpile with warnings:
Argument of type ITestSuite[] is not assignable to parameter of type
Dictionary<{}>. Index signature is missing in ITestSuite[].
How to fix?
Here is the exact warning:
Have you installed the latest type definition for async library?
npm install --save #types/async
I just checked their source and it should accept both array and collection:
export function each<T, E>(arr: T[] | IterableIterator<T>, iterator: AsyncIterator<T, E>, callback?: ErrorCallback<E>): void;
export function each<T, E>(arr: Dictionary<T>, iterator: AsyncIterator<T, E>, callback?: ErrorCallback<E>): void;
export const eachSeries: typeof each;
I think if you install the type definition module and add the definition directory to your tsconfig.json using "typeRoots": ["node_modules/#types"], it should solve the issue.
Edit - Also, you should avoid Array<T> definition for simple types and use T[] instead.

Angular argument assigning issue

I am trying an app in MEAN stack. I have created a contact list for add. edit, update,delete operation using MEAN. When I am trying to get all contacts from my Contact model I am getting the below errors in my code.
Kindly my code below.
import { Component, OnInit } from '#angular/core';
import {ContactService} from '../contact.service';
import {Contact} from '../contact';
#Component({
selector: 'app-contacts',
templateUrl: './contacts.component.html',
styleUrls: ['./contacts.component.css'],
providers: [ContactService]
})
export class ContactsComponent implements OnInit {
contacts: Contact[];
contact:Contact;
first_name:string;
last_name:string;
phone:string;
constructor(private contactService: ContactService) { }
ngOnInit() {
this.contactService.getContacts()
.subscribe( contacts->this.contacts = contacts);
}
}
I got the below errors when I run my application
ERROR in /var/www/html/contactlist/client/src/app/contacts/contacts.component.ts (22,28): Expression expected.
ERROR in /var/www/html/contactlist/client/src/app/contacts/contacts.component.ts (22,43): ',' expected.
ERROR in /var/www/html/contactlist/client/src/app/contacts/contacts.component.ts (22,19): Cannot find name 'contacts'. Did you mean the instance member 'this.contacts'?
ERROR in /var/www/html/contactlist/client/src/app/contacts/contacts.component.ts (22,19): Argument of type 'boolean' is not assignable to parameter of type '(value: any) => void'.
ERROR in /var/www/html/contactlist/client/src/app/contacts/contacts.component.ts (22,19): Operator '>' cannot be applied to types 'number' and 'Contact[]'.
ERROR in /var/www/html/contactlist/client/src/app/contacts/contacts.component.ts (22,45): Cannot find name 'contacts'. Did you mean the instance member 'this.contacts'?
ERROR in ./src/app/contacts/contacts.component.ts
Module parse failed: /var/www/html/contactlist/client/node_modules/#ngtools/webpack/src/index.js!/var/www/html/contactlist/client/src/app/contacts/contacts.component.ts Unexpected token (18:35)
You may need an appropriate loader to handle this file type.
| ContactsComponent.prototype.ngOnInit = function () {
| this.contactService.getContacts()
| .subscribe(contacts - > this.contacts, contacts);
| };
| return ContactsComponent;
# ./src/app/app.module.ts 12:0-66
# ./src/main.ts
# multi webpack-dev-server/client?http://localhost:4200 ./src/main.ts

Resources