首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何告诉TypeScript我知道有一个方法存在?

如何告诉TypeScript我知道有一个方法存在?
EN

Stack Overflow用户
提问于 2021-04-28 19:37:21
回答 2查看 60关注 0票数 2

考虑下面的代码:

代码语言:javascript
复制
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测试中,我得到:

代码语言:javascript
复制
  ● 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?我想告诉译码器我知道我在做什么。

或者,我可以这样做:

代码语言:javascript
复制
if (this.callEndpoint['hasAuthorisationToken'] != undefined) {
    const hasAuth = this.callEndpoint['hasAuthorisationToken']();
    ...
}

然而,我想知道这是不是有点混乱。解决这个问题的最好方法是什么?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-04-28 19:55:54

是的,你的第一个选择是最好的。可读性最强。

代码语言:javascript
复制
if (this.callEndpoint['hasAuthorisationToken'] != undefined) {
    const callEndpoint = this.callEndpoint as CallEndpoint;
    const hasAuth = callEndpoint.hasAuthorisationToken();
    ...
}

不确定!= undefined位。你能用this.callEndpoint instanceof CallEndpoint代替吗?不确定你是如何实例化这些东西的,但是如果你可以使用instanceof,typescript将在没有强制转换的情况下接受对this.callEndpoint方法的调用。如下所示:

代码语言:javascript
复制
if (this.callEndpoint instanceof CallEndpoint) {
    const hasAuth = this.callEndpoint.hasAuthorisationToken();
    ...
}
票数 2
EN

Stack Overflow用户

发布于 2021-04-28 20:09:24

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67299487

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档