11

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()) { ... }
3
  • I'm a fraid not. Especially with javascripts duck typing. Commented Jan 10, 2017 at 8:22
  • 1
    Interfaces are not available at runtime so I don't think know if you can do reflection calls on them. Commented Jan 10, 2017 at 9:02
  • 4
    @toskv That's not the point, that was just an example. I don't want run time, I want compile time. Commented Jan 10, 2017 at 9:46

2 Answers 2

6

There is now: https://typescript-rtti.org/.

import { reflect } from 'typescript-rtti';

interface ITest {
    readonly foo: number;
}

let iface = reflect<ITest>().as('interface').reflectedInterface;
let info = iface.getProperty('foo').type;

expect(info.isReadonly).to.be.true;

Disclaimer: I am the author

Sign up to request clarification or add additional context in comments.

1 Comment

This is beyond incredible. This is game changer.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.