Tom Auger
Tom Auger

Reputation: 20101

Default imports with TypeScript

Using tsc 1.8.9... why are these imports not working? I thought TypeScript implemented ES6 module syntax?

"classes/person.ts"

export default class Person {
    protected _name: string;
    protected _language: string;

    constructor(name: string) {
        this._name = name;

        this.hello();
    }

    public hello() {
        console.log("Hello, " + this._name);
        console.log("Lang: " + this._language);
    }
}

"classes/englishman.ts"

import Person from "person"

export default class Englishman extends Person {
    constructor(name: string){
        this._language = "en_GB";

        super(name);
    }
}

"main.ts"

import * as $ from "jquery";
import Englishman from "classes/englishman";

let tom: Person = new Englishman("Tom");
console.log(tom);


$("body").html(`<h1>TEST</h1>`);

Errors:

source/main.ts(2,24): error TS2307: Cannot find module 'classes/englishman'. source/main.ts(4,10): error TS2304: Cannot find name 'Person'. [13:53:43] TypeScript: 2 semantic errors

Upvotes: 2

Views: 1151

Answers (2)

Angel Angel
Angel Angel

Reputation: 21678

After some changes, it worked for me, tested in ES5 and ES6. I hope to help you:

Original

  1. import Person from "classes/person";
  2. import Englishman from "classes/englishman";

Change for test

  1. import Person from './person';
  2. import Englishman from './classes/englishman';

maybe you need to check your directory tree.

Add

  1. import Person from './classes/person';

.

import Person from './person'; //<-- change

export default class Englishman extends Person {
    constructor(name: string){
        this._language = "en_GB";

        super(name);
    }
}

 export default class Person {
        protected _name: string;
        protected _language: string;

        constructor(name: string) {
            this._name = name;

            this.hello();
        }

        public hello() {
            console.log("Hello, " + this._name);
            console.log("Lang: " + this._language);
        }
    }

import Englishman   from './classes/englishman'; //<-- change
import Person       from './classes/person';     //<-- add

class HelloWorld{
    public static main(){      

        let tom: Person = new Englishman("Tom");
        console.log(tom);

    }
}
HelloWorld.main();

Hello, Tom
Lang: en_GB
Englishman { _language: 'en_GB', _name: 'Tom' }
  • tsc Version 1.8.2
  • node v5.4.1

Upvotes: 0

Justin Drury
Justin Drury

Reputation: 748

Make sure you are compiling with ES6 target, if I'm not mistaken, ES5 is still the default target.

Upvotes: 0

Related Questions