Sushmit Sagar
Sushmit Sagar

Reputation: 1508

error TS2678 Type "'String'" is not comparable to type '""' in angular 5

Here's my code in angular 5:

gotToWallet(wallet) {

  const { countryId = '', currencyType = '' } = wallet || {};

  let walletIdentity;

  switch (currencyType) {
    case 'CRYPTO':
      walletIdentity = 'userWalletIdentity';
     break;
    case 'FIAT':
      walletIdentity = 'fiatWalletIdentity';
     break;
    case 'ERC20TOKEN':
      walletIdentity = 'xbxUserWalletIdentity';
     break;
 }

  const { currencyId = '' } = (wallet || {})[walletIdentity] || {};
  this.router.navigate([`walletMgmt/wallet-details/${currencyId}/${countryId}`]);

}

I am getting the following error when running ng build command:

ERROR in src/app/wallet-management/wallets/wallets.component.ts(202,12): error TS2678: Type '"CRYPTO"' is not comparable to type '""'.
src/app/wallet-management/wallets/wallets.component.ts(205,12): error TS2678: Type '"FIAT"' is not comparable to type '""'.
src/app/wallet-management/wallets/wallets.component.ts(208,12): error TS2678: Type '"ERC20TOKEN"' is not comparable to type '""'.

Why am i getting this error? the code seems to work fine when i run ng serve. I am getting this error only when trying to make build.

Thanks, any help would be highly appreciated.

Upvotes: 6

Views: 21606

Answers (3)

Isolin
Isolin

Reputation: 876

The answer suggested by @QiaosenHuang works but it is not a good practice in terms of TypeScript as it gives up the type-safety being the main goal of TypeScript. The correct way is to pass in a typed wallet for example using an interface.

interface IWallet {
  countryId: string;
  currencyType: string;
  // any other properties ...
}

function gotToWallet(wallet?: IWallet) {
  // your code from the question ...
}

I noted that you test for wallet || {} so that is the reason for using a null coalescing operator for the function argument. But your code actually doesn't do anything when wallet is undefined. So an even better solution would be to require wallet to be a true instance of the interface (wihtout the ?) and move the undefined check outside of this function.

Upvotes: 1

user331244
user331244

Reputation: 611

I just had the same error and it turned out to be triggered by a cyclic import dependency with webpack.

Upvotes: 0

Qiaosen Huang
Qiaosen Huang

Reputation: 1133

switch (currencyType as any) {

for some reason (maybe typescript version?), when you destruct currencyType: '' from wallet, it was interpreted by the compiler as type '""' instead of 'string'. so cast it as any will do the trick

Upvotes: 20

Related Questions