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()) { ... }
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.
Typescript allows an interface to inherit from multiple interfaces. Use the extends keyword to implement inheritance among interfaces.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With