It seems like you are interested in removing properties from a type based on their relation to classes, while keeping non-class
object types. In your example, you remove foo
and doo
(both of type MyClass
) as well as boo
of type MyOtherClass
, but retain coo
of type {x: string;}
.
Unfortunately, achieving this might not be possible.
TypeScript's type system is primarily structural, focusing on the shape of objects rather than their names. The distinction between objects created via different methods (new X()
or Object.create()
or literals) is not significant at the type level or even in runtime JavaScript. What matters most are the properties and methods an object possesses; its shape.
Consider the following comparison:
class Example {
something: string;
constructor(s: string) {
this.something = s;
}
method(): void {
}
}
let ex1 = new Example("ex1");
let ex2 = {
something: "ex2",
method(): void {
}
};
From a typing standpoint, there is no practical difference between ex1
and ex2
, despite minor runtime distinctions. Now, if we introduce these declarations:
let ex3: Example;
let ex4: { something: string; method(): void; };
All of the following assignments are valid:
ex3 = ex1;
ex3 = ex2;
ex4 = ex1;
ex4 = ex2;
ex1 = ex4;
ex2 = ex4;
These types are all compatible with each other, regardless of how they were defined.
While it may seem tempting to utilize the inherited constructor
property of class objects for differentiation, this approach does not yield reliable results. Even objects initialized through literals can have an inherited constructor
property. Therefore, achieving your desired outcome may not be feasible in TypeScript.