I wish to pass in a function as a parameter but limit the passed function’s return type but not its parameters.
Ex: function Car(driver: Function), where driver can be ()=>boolean or (first, second) => boolean. The driver must take a function with return type boolean but have any number of parameters.
Advertisement
Answer
You can make use of generics.
FactoryFunction<T> specifies function type with arbitrary arguments, but a return type of T (or a subtype thereof).
Demo: https://repl.it/@chvolkmann/IdealisticLiveRelationaldatabase
abstract class Vehicle {} // abstract is optional
class Car extends Vehicle {}
class Truck extends Vehicle {}
type FactoryFunction<T> = (...args: any[]) => T
function importVehicle(factory: FactoryFunction<Vehicle>) {
const vehicle = factory() // type: Vehicle
console.log(vehicle)
}
importVehicle(() => new Car())
importVehicle(() => new Truck())
EDIT: You can also make the function itself generic.
function importSomething<T>(factory: FactoryFunction<T>) {
const obj = factory() // type: T
console.log(obj)
}
importSomething(() => new Car())