Generate object from Typescript interface - javascript

I realize this is essentially the opposite intent of Typescript, but I would like to be able to programmatically generate an object FROM a typescript interface. Basically, I want something like this:
interface Foo {
bar: string
}
const generateObjFromInterface = (Foo) => // { bar: 'string'}
I -do not- mind how contrived the implementation is if it IS possible! If it is categorically impossible that would also be helpful information!
Thanks in advance!

It is possible. As typescript 2.4 is around the corner we can use custom transformers for typescript during compilation and get the list of all properties that are there and as a result create object with such properties.
Here is an example, but please note - as I have said this require to use typescript 2.4+ that is not yet in stable release

Since TypeScript's interfaces are not present in the JavaScript output, runtime reflection over an interface is impossible.
Given this TypeScript:
interface Foo {
bar: string
}
This is the resultant JavaScript:
Since there is no JavaScript, what you want to do is categorically impossible is very contrived.
Edit: Come to think of it, you could find, read, and parse the *.ts source file at runtime.

I also was searching for something that could do it and I didn't find anything. So I build this lib https://www.npmjs.com/package/class-validator-mocker, which can generate random data for classes attributes annotated with class-validator's decorators. Worked pretty well for my purposes.

I did it by using intermock (Google)
Here is a demo page

Related

JavaScript interpreter (ES2015 support)

I'm trying to build a JavaScript "visualizer" app, so i need some static and dynamic information.
For example given this code snippet:
class Foo{
constructor(prop){
this.props = prop;
}
}
const x = new Foo('prop');
I would like to be able to "step" through that code and get a sort of an AST including the call-stack, variable environment and results of the function calls.
Parsing it with acorn or other parsers will give me the static AST which is great but obviously won't provide the dynamic information i need like call-stack (when invoking a function) and the returned values etc.
I've used JS-Interpreter and its exactly what i need, but only later i found out it lacks support for ES2015 features, which is a deal breaker for me. I thought maybe run my ES2015 code through babel.transform and pass the transformed ES5 code to JS-Interpreter, then use source-maps to somehow reverse the transformation, but not sure exactly how to do that.
I even thought maybe the Chrome debugger extension API might help me (as devtools has most of what i need) but couldn't see any public methods that can help me with that.
Any ideas?

qx.log.appender Syntax

When declaring qx.log.appender.Native or qx.log.appender.Console, my IDE (PyCharm) complains about the syntax:
// Enable logging in debug variant
if (qx.core.Environment.get("qx.debug"))
{
qx.log.appender.Native;
qx.log.appender.Console;
}
(as documented here)
The warning I get is
Expression statement is not assignment or call
Is this preprocessor magic or a feature of JavaScript syntax I'm not aware yet?
Clarification as my question is ambiguous:
I know that this is perfectly fine JavaScript syntax. From the comments I conclude that here's no magic JS behavior that causes the log appenders to be attached, but rather some preprocessor feature?!
But how does this work? Is it an hardcoded handling or is this syntax available for all classes which follow a specific convention?
The hints how to turn off linter warnings are useful, but I rather wanted to know how this "magic" works
Although what's there by default is legal code, I find it to be somewhat ugly since it's a "useless statement" (result is ignored), aside from the fact that my editor complains about it too. In my code I always change it to something like this:
var appender;
appender = qx.log.appender.Native;
appender = qx.log.appender.Console;
Derrell
The generator reads your code to determine what classes are required by your application, so that it can produce an optimised application with only the minimum classes.
Those two lines are valid Javascript syntax, and exist in order to create a reference to the two classes so that the generator knows to include them - without them, you wouldn't have any logging in your application.
Another way to create the references is to use the #use compiler hint in a class comment, eg:
/**
* #use(qx.log.appender.Native)
* #use(qx.log.appender.Console)
*/
qx.Class.define("mypackage.Application", {
extend: qx.application.Standalone,
members: {
main: function() {
this.base(arguments);
this.debug("Hello world");
}
}
});
This works just as well and there is no unusual syntax - however, in this version your app will always refer to the those log appenders, whereas in the skeleton you are using the references to qx.log.appender.Native/Console were surrounded by if (qx.core.Environment.get("qx.debug")) {...} which means that in the non-debug, ./generate.py build version of your app the log appenders would normally be excluded.
Whether you think this is a good thing or not is up to you - personally, these days I ship all applications with the log appenders enabled and working so that if someone has a problem I can look at the logs (you can write your own appender that sends the logs to the server, or just remote control the user's computer)
EDIT: One other detail is that when a class is created, it can have a defer function that does extra initialisation - in this case, the generator detects qx.log.appender.Console is needed so it makes sure the class is loaded; the class' defer method then adds itself as an appender to the Qooxdoo logging system
This is a valid JS syntax, so most likely it's linter's/preprocessor's warning (looks like something similar to ESLint's no-unused-expressions).
Edit:
For the other part of the question - this syntax most likely uses getters or (rather unlikely as it is a new feature) Proxies. MDN provides simple examples of how this works under the hood.
Btw: there is no such thing as "native" JS preprocessor. There are compilers like Babel or TypeScript's compiler, but they are separate projects, not related to the vanilla JavaScript.

how can I write an annotation for Dart

The question:
What is the procedure to implement an annotation.
How can, or indeed when can one activate the annotation you developed?
I can't seem to find an example or tutorial on how to write a class to implement annotations for dart.
For example with Java you might have an annotation that represents a class that is invoked at compile time and let you modify or inject code. Do Dart annotations work like this as well?
background
I have done some (further) digging on understanding this area of the Dart ecosystem. I'm adding some notes because annotation can be a powerful with transparent commentary on how to use it.
After looking at some actual annotation from Dart, Dart annotations record "a notation" (a label or metadata tags). The question is about how to uses annotations within Dart.
gloaming
My current understanding, based on looking at bits of code, is that they are markers on class objects. It looks like annotations are highly-unstructured since while an annotation can be declared simply, there's no structure to use or recognise a label (aka annotation).
steps of annotation
Identify the property or action you want to label.
Need to write code to use or 'work' your annotation. Look at something like Observe as an example.
You can implement and test LOAD-time code to look-for and process your labels. I don't see an infrastructure to register an annotation and provide handlers for example.
This is done via the main() method in your library.
Implement and test annotation behaviour.
At least I think that's how it works. There's not really a lot of information in the Dart language specification on this area.
Observation and inspection raised a few general questions as well. I've left a reading list of sorts and examples, to assist others in joining the exploration.
readings:
Dart Language Specification
type annotations
metadata
extending a class
I love Dart annotations
zones
zone class
Dart Annotations are No Longer Structured
examples:
Observe
Observable.dart
annotations.dart
Any class with a const constructor can be used as annotation.
const FOO = const Foo(37);
#Foo(42)
class Foo {
#Deprecated("until further notice");
final int x;
#FOO
const Foo(this.x);
}
There is nothing more to it.
See also https://www.dartlang.org/docs/dart-up-and-running/contents/ch02.html#ch02-metadata
Metadata doesn't do anything by itself. If your program wants to read metadata off a class, it needs to use mirrors.
import 'dart:mirrors';
const tag = "TAG";
#tag class C {}
void main() {
print(reflectClass(C).metadata.first.reflectee); // prints "TAG"
var c = new C();
print(reflect(c).type.metadata.first.reflectee); // prints "TAG"
}
See: https://api.dartlang.org/apidocs/channels/stable/dartdoc-viewer/dart-mirrors.ClassMirror#id_metadata
Alternatively, you can process the source directly. For example, the dart2js compiler has a "source mirror" library that reflects over the source structure. It is what dart2js and the analyzer do to understand the "proxy" annotation.

Returns element for Javascript vsdocs

I'm working on fairly heavy client JavaScript application and was looking to add documentation. I went with vsdoc style so as to get picked up by intellisense, but am having trouble defining return objects.
Assuming a function defined as:
function returnObject() {
return { 'prop1': 'value1', method: function(){return 1;}};
}
I'd like to be able to write code as:
returnObject(). and after the . see 'prop1' and 'method' in the intellisense - is this possible without defining an object elsewhere?
How would I define the return object? I've been looking at documentation here, but so far it's been of little help. Looking at the jQuery vsdoc shows me that they almost always return the jQuery object or a simple type. Looking at amplify vsdoc shows that they return Object or undefined and then explain what that object looks like in text.
Can I use the /// element style documentation to define what the return object will look like? Does anyone have any sample of this?
You don't need a vsdoc file for this scenario in visual studio 2012+.
The vsdoc is useful for situations where the internal javascript interpreter can't execute the code, for example web services.
vsdoc files are also useful for when jsdoc style comments are used in the code, and you don't want to have 2 comment formats in the main code files. Jquery is a good example of this.
Also note that vsdoc files are now referred to as intellisense files. However the concept is still the same.
Using inline comments:

Javascript ENUM pattern naming convention

I am working on a javascript project which requires use of javascript "Enums" meaning Objects like:
var WinnerEnum = {
Player1: 1,
Player2: 2,
Draw: 0
};
This is working great for me, however, I have no idea what is the proper way (according to convention) to name the Enum because as far as I know only class names start with a capital letter (indicating the ability to call a constructor on).
JSHint also outputs the following warning:
Missing 'new' prefix when invoking a constructor.
If there is no convention, I would appreciate a good way to name enums that would not confuse them with class names. Update 2014 : JSHint no longer does this.
That is indeed the correct way to name the enum, but the enum values should be ALL_CAPS instead of UpperCamelCase, like this:
var WinnerEnum = {
PLAYER_1: 1,
PLAYER_2: 2,
DRAW: 0
};
This is similar to Java's naming convention for enums.
Some references:
Google JavaScript Style Guide
Stijn de Witt's Blog
Enumify documentation
As with coding style in general, you'll find people doing things in many different ways, with each way having its own set of good reason. To make things easiest for anyone reading and working with your code, however, I would recommend using the style which has the most authoritative reference and therefore usually the most widespread adoption.
I couldn't find any reference more authoritative than Google's style guide and the writings above, written by people who have given some serious thought to enums, but I'd be interested to hear of any better references.
According to Google's coding conventions this is the correct way indeed to name an enum in javascript.
As requested here is a link.
First, there is no "correct" way* of declaring a pseudo-enum in JS. You should strive to be consistent within your existing code base and/or your organization's conventions if possible.
One popular convention is Google JavaScript Style Guide. E.g.:
const TemperatureScale = {
CELSIUS: 'celsius',
FAHRENHEIT: 'fahrenheit',
};
Curiously, this is inconsistent with MDN's hidden convention for const, as in Google's example, TemperatureScale is a const and TemperatureScale.CELSIUS is not!
* it must be a valid JavaScript identifier.

Categories

Resources