首页 > 解决方案 > 在 TypeScript 中,如何使用位于另一个文件中的类

问题描述

我对 typescript namespaces , modules 有点困惑。我需要解决一个简单的任务 - 创建两个打字稿文件并使用另一个类。但是,我如何让它工作。

结构 :

 installation :
          typescript :
                Person.ts
                main.ts

main.ts 的代码是

//Using this tag I am trying to load another file
/// <reference path = "Person.ts" />

var person:Person = new Person("Sergey" , "Sckoriy");
console.log(person.greet());

Person.ts 的代码是

export class Person {
    name : string;
    surname : string;

    constructor (name : string , surname : string){
        this.name = name;
        this.surname = surname;
    }

    greet():string {
        var text:string = "Hello" + this.name;
        return text;
    }
}

但是,当它被编译时

  ..../tsc main.ts

有错误,例如:

main.ts:3:12 - error TS2304: Cannot find name 'Person'.
3 var person:Person = new Person("Sergey" , "Sckoriy");
main.ts:3:25 - error TS2552: Cannot find name 'Person'. Did you mean 'person'?
3 var person:Person = new Person("Sergey" , "Sckoriy");
main.ts:3:5
3 var person:Person = new Person("Sergey" , "Sckoriy");
      ~~~~~~
'person' is declared here.

 Found 2 errors.

实际上,我已经引用了另一个带有标签的文件,但它不起作用......这里有什么问题?

标签: typescript

解决方案


import { Person } from './Person


推荐阅读