如何在TypeScript中运行包含接口inter.ts的call.ts

时间:2019-06-08 12:24:52

标签: typescript

我正在使用VS Code 1.34.0,并且正在学习TypeScript,并且尝试运行包含接口inter.ts的call.ts文件。

我已经尝试过使用tsc call.ts及其转换,但是当我尝试提供命令call.js时却不起作用。

//inter.ts
export interface IEmployee {
  empCode: number; 
  empName: string;
  sayHi(): string; 
}

//call.ts
import {IEmployee} from'E:/TypeScript/InterphaseExample/inter';

class Called {

  constructor() {
    var customer:IEmployee = { 
      empCode:1,
      empName:"Hanks", 
      sayHi: ():string =>{return "Hi there"} 
    }

    console.log("Customer Object "); 
    console.log(customer.empCode); 
    console.log(customer.empName); 
    console.log(customer.sayHi());     
  }  
}

预期结果应为:1, Hanks, Hi There!
实际结果:不起作用

1 个答案:

答案 0 :(得分:0)

假设您的项目结构如下:

enter image description here

tsconfig.json

将此文件放在项目的根目录下,对不起,我忘记将此文件添加到屏幕截图上。

{
    "compilerOptions": {
        /* Basic Options */
        "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
        "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
        "outDir": "./dist",                        /* Redirect output structure to the directory. */
        "rootDir": "./project",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
        "strict": true,                           /* Enable all strict type-checking options. */
        "esModuleInterop": true                   /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    }
}

inter.interface.ts

export interface IEmployee {
    empCode: number; 
    empName: string;
    sayHi(): string; 
}

call.ts

import { IEmployee } from "./interfaces/inter.interface";

class Called {

    constructor() {
        const customer: IEmployee = {
            empCode: 1,
            empName: "Hanks",
            sayHi: (): string => {
                return "Hi there"
            }
        }

        console.log("Customer Object ");
        console.log(customer.empCode);
        console.log(customer.empName);
        console.log(customer.sayHi());
    }
}


const a = new Called();

然后在您的cmd中运行此命令

  • tsc --watch
  • node ./dist/call.js