As someone who has primarily worked with C#, TypeScript is a new and exciting challenge for me. I've been enjoying exploring what I can create quickly using Node/TypeScript. However, I've run into a syntax issue that I could use some help with. I have an interface that two concrete classes implement, and another module that exports one of these classes based on configuration.
fruit.ts
export interface Fruit {
eat();
}
apple.ts
export class Apple implements Fruit {
eat() { console.log('Eat apple'); }
}
banana.ts
export class Banana implements Fruit {
eact() { console.log('Eat banana'); }
}
breakfast.ts
import { Fruit } from 'fruit';
import { Apple } from 'apple';
import { Banana } from 'banana';
const BreakfastType: typeof Fruit = config.appleForBreakfast ? Apple : Banana; <-- Error
export { BreakfastType }
On paper, this setup seems like it should function correctly. After all, Apple and Banana are both "types of fruit," so declaring BreakfastType as "typeof Fruit" makes sense to me. However, TypeScript is throwing an error:
Fruit only refers to a type, but is being used as a value here
While this example might seem contrived, it reflects my current coding dilemma perfectly. Ultimately, I want the following code to be able to work:
import { BreakfastType } from 'breakfast';
let breakfastFood = new BreakfastType(); <-- create Apple or Banana based on config
If anyone has any suggestions, I would greatly appreciate your input!