Reputation: 31
not sure it's even possible but might be there is a way in typescript to implement type constraint for class instances only but not object. To make the example below possible:
class EmptyClass {}
class ClassWithConstructorParams {
constructor (public name: string) {}
}
function theFunction<SomeConstraint>(arg: SomeConstraint): void {
// todo: do something
}
theFunction(new EmptyClass()); // should be OK
theFunction(new ClassWithConstructorParams('foo')); // should be OK
theFunction({}) // should be COMPILE ERROR
theFunction({name:'foo'}); // should be COMPILE ERROR
// obviously should also prevent numbers, string, delegates and etc
theFunction(''); // should be COMPILE ERROR
theFunction(1); // should be COMPILE ERROR
theFunction(EmptyClass); // should be COMPILE ERROR
theFunction(theFunction); // should be COMPILE ERROR
So far I managed a filter to allow only instances, but it accepts both class instance and object {}. Need to prevent objects.
Thanks in advance
Upvotes: 1
Views: 327
Reputation: 249666
There is no general way to do this, Typescript uses structural typing and as long as the object literal satisfies the constraint of the function it will be valid as an argument.
If you have a common base class for the classes you want to pass to the function, you can add a private field to it. No other class or object literal will be able to satisfy the constraint of a class with a private field except a class derived from that class.
class EmptyClass {
private notStructural: undefined
}
class ClassWithConstructorParams extends EmptyClass {
constructor(public name: string) {
super()
}
}
class OtherClass{
private notStructural: undefined
}
function theFunction<T extends EmptyClass>(arg: T): void {
// todo: do something
}
//.constructor
theFunction(new EmptyClass()); // should be OK
theFunction(new ClassWithConstructorParams('foo')); // should be OK
theFunction(new OtherClass()) // error not the same private field
theFunction({ notStructural: undefined }) // error
theFunction({}) // ERROR
theFunction({name:'foo'}); // ERROR
Upvotes: 1