考虑下面的代码:
export default class OptimizelyFeatureFlags implements FeatureFlags {
private body: string;
constructor(
protected callEndpoint: CacheableEntity,
protected baseUrl: string,
protected envName: string,
protected featureId: string
) {}
/**
* Calls the Optimizely endpoint to get the info
*/
public async fetch(): Promise<void> {
// Determine if this is a CallEndpoint (or child thereof)
if (this.callEndpoint['hasAuthorisationToken'] != undefined) {
if (!this.callEndpoint.hasAuthorisationToken()) {
throw Error(
'This endpoint requires an auth token to work'
);
}
}
this.body = await this.callEndpoint.getResource(this.baseUrl + `/v2/features/${this.featureId}`);
}
...
}现在CacheableEntity是一个接口,它只需要getResource()来匹配约定。方法hasAuthorisationToken未在其中定义。
现在,如果一个类有一个hasAuthorisationToken()方法,我知道它是一个CallEndpoint,它将实现CacheableEntity。这是一个类型测试--根据我的研究,我知道TypeScript不提供运行时类型测试,因为在运行时它仅仅是JavaScript。
但是,这不会编译。在Jest测试中,我得到:
● Test suite failed to run
src/service/feature-flags/OptimizelyFeatureFlags.ts:31:36 - error TS2339: Property 'hasAuthorisationToken' does not exist on type 'CacheableEntity'.
31 if (!this.callEndpoint.hasAuthorisationToken()) {
~~~~~~~~~~~~~~~~~~~~~我猜有几种方法可以解决这个问题--也许我可以将对象从CacheableEntity转换为CallEndpoint?我想告诉译码器我知道我在做什么。
或者,我可以这样做:
if (this.callEndpoint['hasAuthorisationToken'] != undefined) {
const hasAuth = this.callEndpoint['hasAuthorisationToken']();
...
}然而,我想知道这是不是有点混乱。解决这个问题的最好方法是什么?
发布于 2021-04-28 19:55:54
是的,你的第一个选择是最好的。可读性最强。
if (this.callEndpoint['hasAuthorisationToken'] != undefined) {
const callEndpoint = this.callEndpoint as CallEndpoint;
const hasAuth = callEndpoint.hasAuthorisationToken();
...
}不确定!= undefined位。你能用this.callEndpoint instanceof CallEndpoint代替吗?不确定你是如何实例化这些东西的,但是如果你可以使用instanceof,typescript将在没有强制转换的情况下接受对this.callEndpoint方法的调用。如下所示:
if (this.callEndpoint instanceof CallEndpoint) {
const hasAuth = this.callEndpoint.hasAuthorisationToken();
...
}发布于 2021-04-28 20:09:24
https://stackoverflow.com/questions/67299487
复制相似问题