Reputation: 362
I have just started with Typescript for a front-end web project. My goal is to use a OOP approach. So my convention is one class by file (named from the class it contains).
Consider this example:
//Car.ts
export default class Car {
public startEngine (): void {
console.log('vroom!');
}
}
//RaceCar.ts
import Car from './Car';
export default class RaceCar extends Car {
public startEngine (): void {
console.log('!!VROOOOOMM!!');
}
}
//index.ts
import RaceCar from './RaceCar';
import Car from './RaceCar';
const car:Car = new RaceCar();
car.startEngine();
This code works fine but I have 2 questions:
import Car from './Car';
. Is there a short way to do this? Like a macro or something? I have tried import './Car';
but of course this does not import Car
symbol...In other words I am looking for a way to do something like a C++ include.
Upvotes: 2
Views: 4270
Reputation: 85112
When I use the convention "one class per file" (with default export) it is really annoying to write import Car from './Car';. Is there a short way to do this? Like a macro or something? I have tried import './Car'; but of course this does not import Car symbol...
To use the Car, the code will have to say import Car from './Car'
. This syntax basically means "run the code in ./Car, and assign its default export to Car
". import './Car'
is legal, but it means "run the code in ./Car, but i don't need to use what it exports".
That said, various IDEs can help you fill the import in automatically. For example, i use Visual Studio Code, and if i use Car
somewhere in my code without importing or defining it, i get the red underline and can then press ctrl-space to automatically import it in most cases.
Another annoying thing is to import Car and RaceCar in index.ts. Is there a way to import only RaceCar that already knows the Race class?
If you need to directly reference any of the things exported by the Car file, then you'll need to import it. In your example, you're using Car as a type. If you need that, then you need to import it. That said, in your situation i'd probably just use RaceCar as the type, since that's what you're newing up anyway.
import RaceCar from './RaceCar';
const car: RaceCar = new RaceCar();
car.startEngine();
Upvotes: 2
Reputation: 6799
TypeScript uses +ES6 syntax:
According to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import
Import an entire module for side effects only, without importing anything. This runs the module's global code, but doesn't actually import any values.
import '/modules/my-module.js';
You need to import the symbol you want to use:
import myDefault from '/modules/my-module.js'; // myDefault is the default exported symbol in the module.
Therefore, no. You always need to import the symbol you want to use explicitly and only from these code places where you need to use them.
Upvotes: 2