0

My background comes from Objective-C where you can specify types that have both classes and interfaces in them. I can't seem to find any documentation that shows this in TypeScript, but it must exist, right?

Here's an example:

class Vehicle {}
class Car extends Vehicle {}
class Truck extends Vehicle {}

interface Electric{}

// These next lines are WRONG!
ChargeMyCar(car: Car<Electric>) { ... }
ChargeMyTruck(truck: Truck<Electric>) { ... }

Is this possible? What's the syntax?

How about a type that has multiple interfaces?

1
  • 1
    Brent - after reading your question a few times, I'm not sure what you're looking for. Perhaps you could show what code you're using in Objective-C and then it might be clearer what the similar TypeScript would be. Commented Dec 22, 2014 at 20:43

1 Answer 1

2

It really depends on what you are trying to do with the Electric interface. You can use the following syntax:

class Vehicle {
    fuel: any;
}
class Car<T> extends Vehicle {
    fuel: T;
}
class Truck<T> extends Vehicle {
    fuel: T;
}

interface Electric {}

ChargeMyCar<T extends Electric>(car: Car<T>) { ... }
ChargeMyTruck<T extends Electric>(truck: Truck<T>) { ... }

The above example shows that a car/truck takes an abstract type of fuel, and in order to "charge" a car/truck, you must have a car/truck with Electric type fuel. Kind of a silly example, but do you understand the syntax?

Multiple interfaces is easy, if you wanted to use multiple interfaces instead you could just do the following:

class Vehicle {
    fuel: any;
}
class Car extends Vehicle { }
class Truck extends Vehicle { }

interface Electric { }

class ElectricCar implements Vehicle, Electric { }
class ElectricTruck implements Vehicle, Electric { }

ChargeMyCar(car: ElectricCar) { ... }
ChargeMyTruck(truck: ElectricTruck) { ... }
Sign up to request clarification or add additional context in comments.

2 Comments

After looking around a bunch more, I think this is the right answer. I didn't expect to have to make an ElectricCar and ElectricTruck type, but it seems like it's the easiest answer.
another implementation could be class ElectricCar extends Car implements Electric { }, this may be what you're looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.