Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript reflection for interfaces

Is there a way to find out if interface's property is defined as read only? Say,

interface ITest {
    readonly foo: number;
}

Now, is there some sort of reflection or trickery for TypeScript to get this information? E.g. something like:

let info = Reflect.get(ITest, 'foo');

if (info.isReadOnly()) { ... }
like image 699
nhaa123 Avatar asked Jan 10 '17 08:01

nhaa123


People also ask

Does TypeScript have reflection?

It is pretty advanced ReflectionReflectionIn computer science, reflective programming or reflection is the ability of a process to examine, introspect, and modify its own structure and behavior.https://en.wikipedia.org › wiki › Reflective_programmingReflective programming - Wikipedia system for TypeScript (using custom typescript transformer plugin). Check Synopsis. You are able to create instances of those types (even they are from different files) and call those methods.

Does TypeScript support interfaces?

Typescript allows an interface to inherit from multiple interfaces. Use the extends keyword to implement inheritance among interfaces.

Should I use type or interface TypeScript?

Interfaces are most recommended for defining new objects or methods or properties of an object where it will receive a specific component. Hence interface works better when using objects and method objects. Therefore it is our choice to choose between types or interface according to the program needs.

How do you define an array in TypeScript interface?

To define an interface for an array of objects, define the interface for the type of each object and set the type of the array to be Type[] , e.g. const arr: Employee[] = [] . All of the objects you add to the array have to conform to the type, otherwise the type checker errors out.


1 Answers

Since TypeScript interfaces do not exist at runtime, you cannot use reflection on them. To use reflection I created a class that implements the interface and reflected on the class. However, I was unable to tell if a property is readonly. Not sure if this is a lack of understanding on my part, or a defect. Here is what I tried:

Code

interface ITest {
  readonly foo: number;
  bar: number;
}
class TestImplementation implements ITest {
  readonly foo: number = 1;
  bar: number = 2;
}
function reflectOnTest() {
  var testImplementation = new TestImplementation();
  var properties: string[] = Object.getOwnPropertyNames(testImplementation);
  var fooDescriptor = Object.getOwnPropertyDescriptor(testImplementation, properties[0]);
  var barDescriptor = Object.getOwnPropertyDescriptor(testImplementation, properties[1]);
  console.log("foo writable = " + fooDescriptor.writable);
  console.log("bar writable = " + barDescriptor.writable);
}

Output is:

foo writable = true

bar writable = true

like image 55
frankl5150 Avatar answered Oct 07 '22 23:10

frankl5150