Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get type of properties unique to a child class

Tags:

typescript

Is it possible to construct a TypeScript type that extracts the property names that are unique to a specific class, that it did not inherit from its parent class? For instance, this works if I know the parent class (Playground Link):

class Parent {
    hello = 'hello'
}

class Child extends Parent {
    world = 'world'
}

type OwnProps<Base, T extends Base> = Exclude<keyof T, keyof Base>

declare const ownProps: OwnProps<Parent, Child> // "world"

However, I would like a way to accomplish the same type of thing, but without explicitly specifying the base class, something like this:

type OwnProps<T, Base = T extends ???> = Exclude<keyof T, keyof Base>

declare const ownProps: OwnProps<Child> // "world"

Is this possible? Is there some kind of conditional magic I can use in place of ??? that would let me infer types that the Child class extends?

like image 873
Jacob Gillespie Avatar asked May 28 '20 19:05

Jacob Gillespie


People also ask

Does the parent class inherit the child's class properties Why?

Inheritance allows us to define a class that inherits all the methods and properties from another class. Parent class is the class being inherited from, also called base class. Child class is the class that inherits from another class, also called derived class.

Can we have same method in child class?

Since the method is not virtual, there is no problem to have the same name. Which one is called depends merely on the type of the reference.

Can child class have same method name as parent class?

Yes, parent and child classes can have a method with the same name.

How to declare class in TypeScript?

Example: Declaring a classThe var keyword is not used while declaring a field. The example above declares a constructor for the class. A constructor is a special function of the class that is responsible for initializing the variables of the class. TypeScript defines a constructor using the constructor keyword.


1 Answers

Unfortunately it looks impossible. TypeScript uses structural type system and a type doesn't store any information about class hierarchy, i.e. the Child type it's just { hello: string, world: string }.

You can also look at the other similar question: TypeScript: Get Type of Super Class?

like image 65
Valeriy Katkov Avatar answered Oct 21 '22 20:10

Valeriy Katkov