下面是我在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}`]);
}运行ng build命令时出现以下错误:
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 '""'.为什么我会得到这个错误?当我运行ng serve时,代码似乎运行得很好。只有在尝试构建时,我才会遇到这个错误。
谢谢,任何帮助都将不胜感激。
发布于 2019-03-06 17:45:47
switch (currencyType as any) {
由于某种原因(可能是typescript版本?),当您从wallet中析构currencyType: ''时,编译器会将其解释为类型'""‘而不是'string’。所以,就像任何人都能达到目的一样
发布于 2020-06-17 20:54:43
@乔森黄建议的答案是有效的,但它不是一个好的TypeScript实践,因为它放弃了类型安全是TypeScript的主要目标。正确的方法是传入一个类型化的wallet,例如使用一个接口。
interface IWallet {
countryId: string;
currencyType: string;
// any other properties ...
}
function gotToWallet(wallet?: IWallet) {
// your code from the question ...
}我注意到您测试的是wallet || {},所以这就是使用null coalescing operator作为函数参数的原因。但是当wallet为undefined时,您的代码实际上不会执行任何操作。因此,一个更好的解决方案是要求wallet成为接口的真实实例(没有?),并将undefined检查移到此函数之外。
发布于 2019-10-07 18:12:54
我刚刚遇到了同样的错误,事实证明它是由与webpack的循环导入依赖项触发的。
https://stackoverflow.com/questions/55018730
复制相似问题