Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between Reflect.getMetadata and Reflect.getOwnMetadata?

As said in the title: the reflect-metadata API provides a getMetadata method and a getOwnMetadata - what's the difference here? Same goes for hasOwnMetadata, etc.

like image 288
nehalist Avatar asked Jan 29 '18 20:01

nehalist


People also ask

What is use of reflect-metadata?

reflect-metadata Allows you to do runtime reflection on types. The native (non reflect-metadata) version of type inference is much poorer than reflect-metadata and consists only of typeof and instanceof .

What is reflect-metadata in TypeORM?

With the reflect-metadata package you can do runtime reflection on types. Since TypeORM mostly works with decorators (like @Entity or @Column), this package is used to parse these decorators and use it for building sql queries.

Does typescript have reflection?

Summary. The reality is that Typescript Reflection is very poor. In order to get a very basic set of Reflection features — we need to make a number of hacky solutions. Other than Dependency Injection tools, I see no other use for this limited functionality.


1 Answers

Generally the different between the Own versions and the regular ones is whether the lookup continues up the prototype chain. In the own versions, only metadata defined specifically on the target object is found. In the regular versions if the metadata was not defined on the target object, metadata defined on the prototype of the object is returned.

Example :

@Reflect.metadata("key", "base value")
class B {
    get prop(): number { return 0; }
}

class C extends B{ }

// "base value", metadata was not defined on C but was defined on it's prototype B
console.log(Reflect.getMetadata("key", C)); 

// undefined, metadata was not defined on C
console.log(Reflect.getOwnMetadata("key", C)); 
like image 79
Titian Cernicova-Dragomir Avatar answered Sep 28 '22 07:09

Titian Cernicova-Dragomir