【问题标题】:Property X does not exist on type Y when using static class property使用静态类属性时,类型 Y 上不存在属性 X
【发布时间】:2018-03-29 04:36:21
【问题描述】:

当我想访问某个模块中的静态类属性时遇到打字稿错误问题。

假设我想导出一些具有静态属性的类:

// MODULE 1
export class AppConfig {
  static readonly apiKey: string = process.env.API_KEY;
}

在模块 2 中,我为某个对象创建了一个接口;

// MODULE 2
import { AppConfig } from "./appConfig";

interface AppContext {
  config: AppConfig;
  ...
}

export default class App {
 ...

 get ctx(): AppContext {
  return {
    config: AppConfig,
    ...
  };
 }

 ...
}

在模块 3 中,我终于想访问该属性:

// MODULE 3
...    
function createContext(app: App): object {
  return Object.assign(app.ctx, {
    apiContext: app.ctx.config.apiKey
  });
}
...

然后我得到 TS 错误: “'AppConfig'类型上不存在属性'apiKey'。”,这很奇怪,因为该属性无疑在这种类型上。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    静态属性不能通过类实例访问。它应该通过类标识符访问,如下所示:

    const key = AppConfig.apiKey;
    

    Static Properties

    【讨论】:

      【解决方案2】:

      主要问题是 config 参数被声明为 AppConfig 的实例:

      config: AppConfig;
      

      但实际上并非如此。

      我建议考虑另一种方法来声明此参数。例如:

      interface IApiKeyProvider {
          apiKey: string;
      }
      
      interface AppContext {
        config: IApiKeyProvider;
      }
      

      【讨论】:

      • 实际上,我已经实现了建议的方法,但我认为应该有另一种方法可以在不使用接口的情况下实现所需的输出。我猜没有...
      猜你喜欢
      • 1970-01-01
      • 2016-11-14
      • 2020-11-24
      • 2019-02-26
      • 2021-09-19
      • 1970-01-01
      相关资源
      最近更新 更多