如何在打字稿中的对象中使用类变量?

工作

假设我在打字稿文件中有一个类,如下所示:

export class app {
  let variable3="Hellow world"
  constructor(count){
      this.variable1="something",
      this.variable2=1+count;
   }

}

现在在另一个文件中,我将此类导出为:

import { app } from './directory';
let pageApp:app;

现在,如何在这里访问这些变量?

提香·切尔尼科娃·德拉戈米尔

您对类的定义在语法上不正确,let在类中不存在,在语义上不正确,您需要声明所有字段:

// appClass.ts
export class app {
    variable1: string // implicitly public in typescript
    variable2: number
    variable3 = "Hellow world"
    constructor(count : number) {
        this.variable1 = "something";
        this.variable2 = 1 + count;
    }

} 

关于用法,导入应该可以,但是您需要导入该类所在的文件(而不是您的导入所建议的目录),并且需要更新该类以创建实例。

import { app } from './appClass'; // notice no extension (no .js or .ts)
let pageApp:app = new app(1);
console.log(pageApp.variable2);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章