【发布时间】:2021-04-26 05:29:42
【问题描述】:
我收到了许多与在我的 Typscript 代码中使用“any”作为函数返回类型有关的警告。我正在尝试使用 Cloud Functions for Firebase 编写 node.js 后端,以管理 Google Play Billing 购买和订阅。 我正在遵循 Classy Taxi Server 示例中给出的示例: https://github.com/android/play-billing-samples/tree/main/ClassyTaxiServer
例如:
function purchaseToFirestoreObject(purchase: Purchase, skuType: SkuType): any {
const fObj: any = {};
Object.assign(fObj, purchase);
fObj.formOfPayment = GOOGLE_PLAY_FORM_OF_PAYMENT;
fObj.skuType = skuType;
return fObj;
}
发出警告
出乎意料。指定不同的类型。 @typescript-eslint/no-explicit-any)
我尝试将“any”更改为“unknown”,但出现错误
类型“未知”.ts(2339) 上不存在属性“formOfPayment”
和
类型“未知”.ts(2339) 上不存在属性“skuType”
在另一个函数中
export function mergePurchaseWithFirestorePurchaseRecord(purchase: Purchase, firestoreObject: any) {
// Copy all keys that exist in Firestore but not in Purchase object, to the Purchase object (ex. userID)
Object.keys(firestoreObject).map(key => {
// Skip the internal key-value pairs assigned by convertToFirestorePurchaseRecord()
if ((purchase[key] === undefined) && (FIRESTORE_OBJECT_INTERNAL_KEYS.indexOf(key) === -1)) {
purchase[key] = firestoreObject[key];
}
});
}
我收到以下警告
函数缺少返回类型。 @typescript-eslint/explicit-module-boundary-types
参数“firestoreObject”应使用非任何类型键入。 @typescript-eslint/explicit-module-boundary-types
出乎意料。指定不同的类型。 @typescript-eslint/no-explicit-any
在这个函数中,如果我将“any”更改为“unknown”,我仍然会收到警告
函数缺少返回类型。
在另一个示例中,我在此构造函数中使用“any”时遇到错误:
export default class PurchaseManager {
constructor(private purchasesDbRef: CollectionReference, private playDeveloperApiClient: any) { }
又是警告
参数“playDeveloperApiClient”应使用非任何类型键入。 @typescript-eslint/explicit-module-boundary-types
在这种情况下,如果我按照建议使用“未知”而不是“任何”,那么我会在以下函数中收到“购买”错误:
const apiResponse = await new Promise((resolve, reject) => {
this.playDeveloperApiClient.purchases.products.get({
packageName: packageName,
productId: sku,
token: purchaseToken,
}, (err, result) => {
if (err) {
reject(this.convertPlayAPIErrorToLibraryError(err));
} else {
resolve(result.data);
}
})
});
在构造函数中将“any”更改为“unknown”产生的错误是:
类型“未知”.ts(2339) 上不存在属性“购买”
如果我理解正确,我可以通过禁用整个文件的显式模块边界类型和/或 no-explicit-any 来防止所有这些(和其他类似)警告而不会产生错误,但我是不确定这是不是不好的做法?
是否有另一种(更好的)方法来指定返回类型以避免使用“any”? 还是继续禁用显式模块边界类型或无显式任何是否可以?
【问题讨论】:
标签: node.js typescript firebase google-cloud-functions in-app-billing