Prototypes in Javascript to Typescript Syntax - javascript

Does somebody know how do I write this Javascript code into Typescript? Especially the prototype inside of the class causes me problems...
var Module = (function () {
function Module(name) {
this.name = name;
}
Module.prototype.toString = function () {
return this.name;
};
return Module;
})();
var Student = (function () {
function Student(name, studentNumber) {
this.bookedModules = [];
this.name = name;
this.studentNumber = studentNumber;
}
Student.prototype.bookModule = function (bookedModule) {
this.bookedModules.push(bookedModule);
};
Student.prototype.bookedModuleNames = function () {
return this.bookedModules.map(function (module) {
return module.toString();
});
};
return Student;
})();

In typescript you use classes, the compiler will do the prototype work for you.
You code is equivalent to:
class Module {
public name: string;
constructor(name: string) {
this.name = name;
}
toString(): string {
return this.name;
}
}
class Student {
public name: string;
public studentNumber: number;
public bookedModules: Module[];
constructor(name: string, studentNumber: number) {
this.name = name;
this.bookedModules = [];
this.studentNumber = studentNumber;
}
bookModule(book: Module): void {
this.bookedModules.push(book);
}
bookedModuleNames(): string[] {
return this.bookedModules.map(book => book.name);
}
}
(code in playground)
Which compiles into:
var Module = (function () {
function Module(name) {
this.name = name;
}
Module.prototype.toString = function () {
return this.name;
};
return Module;
}());
var Student = (function () {
function Student(name, studentNumber) {
this.name = name;
this.bookedModules = [];
this.studentNumber = studentNumber;
}
Student.prototype.bookModule = function (book) {
this.bookedModules.push(book);
};
Student.prototype.bookedModuleNames = function () {
return this.bookedModules.map(function (book) { return book.name; });
};
return Student;
}());

Use classes - typescript will generate this code for you:
class Module {
constructor(public name) {
}
toString() {
return this.name;
}
}
class Student {
bookedModules: Module[];
constructor(public name, public studentNumber) {
this.bookedModules = [];
}
bookModule(bookedModule: Module) {
this.bookedModules.push(bookedModule);
}
//...
}

Related

Typescript not compiling class properties

I have a problem with typescript. The problem is that it suddenly stopped compiling class properties to the .js file. It compiles everything, the functions the constructor but the properties aren't there.
Server.ts
export class Server{
id: String;
prefix: String;
constructor(){
}
copy(object){
object = JSON.parse(JSON.stringify(object));
console.log(this);
for (const k in object) {
if(this.hasOwnProperty(k))
this[k] = object[k];
}
console.log(this);
}
}
Server.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Server = void 0;
class Server {
constructor() {
}
copy(object) {
object = JSON.parse(JSON.stringify(object));
console.log(this);
for (const k in object) {
if (this.hasOwnProperty(k))
this[k] = object[k];
}
console.log(this);
}
}
exports.Server = Server;
Scenario.ts
import { percentageChance } from "../utilities/percentageChance";
import { Champion } from "./Champion";
export class Scenario {
name: String;
description: String;
champion: Champion;
choices: string[];
outcome: number[];
final: string[];
constructor(name: String, description: string | String, champion: Champion, choices: string[], outcome: number[], final: string[]) {
this.name = name;
this.description = description;
this.champion = champion;
this.choices = choices;
this.outcome = outcome;
this.final = final;
}
calculateOutcome(choiceIndex : number) {
if(percentageChance(this.choices, this.outcome) == this.choices[choiceIndex]){
return true;
}
return false;
}
}
Scenario.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Scenario = void 0;
const percentageChance_1 = require("../utilities/percentageChance");
class Scenario {
constructor(name, description, champion, choices, outcome, final) {
this.name = name;
this.description = description;
this.champion = champion;
this.choices = choices;
this.outcome = outcome;
this.final = final;
}
calculateOutcome(choiceIndex) {
if (percentageChance_1.percentageChance(this.choices, this.outcome) == this.choices[choiceIndex]) {
return true;
}
return false;
}
}
exports.Scenario = Scenario;
Has anyone had anything like this happened? If yes then how should it fix this?
I think that one is easy, as JS is a dynamically typed language no property that was not assigned a value will be created. So typescript will leave those properties to be created on-demand.
If you put a default value in class properties, it makes them transpile to JS on compile time.
export class Scenario {
name: String = '';
description: String = '';
champion: Champion = new Champion();
choices: string[] = [];
outcome: number[] = [];
final: string[] = [];
//...
}
Had the same problem using a method to copy properties of the same values from another object, since my properties do not exist (because of absent default value) nothing was copied...

Parent static method to return subclass object

class Vehicle {
constructor (name, type) {
this.name = name;
this.type = type;
console.log(this.constructor.name);
}
getName () {
return this.name;
}
getType () {
return this.type;
}
static create(name, type) {
return new Vehicle(name, type);
}
}
class Car extends Vehicle {
constructor (name) {
super(name, 'car');
}
getName () {
return 'It is a car: ' + super.getName();
}
}
let car = Car.create('Tesla', 'car');
console.log(car.getName()); // It is a car: Tesla
console.log(car.getType()); // car
The above code use ES6 class keyword to define a Vehicle class and a subclass Car from it. How to return Car instance from Vehicle static method.
Try:
let car = new Car('Tesla')
You can pass the ClassName you want to use within your static function create and create an instance from it.
static create(name, type, objClass) {
return new Function(`return new ${objClass ? objClass : 'Vehicle'}('${name}', '${type}');`)();
}
The Function class receives a String with the expression to evaluate, in your case:
new Function(`return new ${objClass}('${name}', '${type}');`)()
Look at this code
class Vehicle {
constructor(name, type) {
this.name = name;
this.type = type;
}
getName() {
return this.name;
}
getType() {
return this.type;
}
static create(name, type, objClass) {
return new Function(`return new ${objClass ? objClass : 'Vehicle'}('${name}', '${type}');`)();
}
}
class Car extends Vehicle {
constructor(name) {
super(name, 'car');
}
getName() {
return 'It is a car: ' + super.getName();
}
}
let car = Car.create('Tesla', 'car', 'Car');
console.log(car.getName()); // It is a car: Tesla
console.log(car.getType()); // car
let superCar = Vehicle.create('Tesla', 'car');
console.log(superCar.getName()); // Tesla
console.log(superCar.getType()); // car
.as-console-wrapper {
max-height: 100% !important
}
See? now is printing the right output.
Resources
Class Function

How to export Typescript class in Node.js with parameter

What I need is Typescript equivalent of
require('mytypescriptfile')(optionsObject);
But TS code:
export class Animal {
name: string;
public bark(): string {
return "bark " + this.name;
}
constructor(color:string) { }
}
Produces this JS code:
"use strict";
var Animal = (function () {
function Animal(color) {
}
Animal.prototype.bark = function () {
return "bark " + this.name;
};
return Animal;
}());
exports.Animal = Animal;
No place for parameter in generated function. How do I do it?
const myTypescriptModule = require('myCOMPILEDtypescriptfile.js');
const whatIWant = new myTypescriptModule.Animal('red')

Including Typescript code in Relay (System.js import)

How to include system.js to fix the error below? Or is there any other solution?
I downloaded the relay-starter-kit (https://github.com/relayjs/relay-starter-kit), changed the database.js to database.ts with the below content (Snippet 1).
I ran "npm run update-schema" and got the error
System.register([], function (exports_1) {
^
ReferenceError: System is not defined
at Object.<anonymous> (database.js:9:1)
at Module._compile (module.js:410:26)
..
I know it occurs because update-schema uses scripts/updateSchema.js -> data/schema.js -> which imports objects from data/database.js (compiled version of database.ts) has -
System.register([], function(exports_1) {
Snippet 1:
/// <reference path="./interface.d.ts" />
export class User implements IUser{
constructor (public id: String, public name: String){
this.id = id;
this.name = name;
}
}
// Model types
class UserModel extends User implements IUserModel {
constructor(public id: String, public name: String){
super (id,name);
}
getUser ():IUser{
return this;
}
setUser (_User:IUser) : void {
this.id = _User.id;
this.name = _User.name;
}
getUserbyId (_id:String):IUser{
if (_id === this.id){
return this;
} else {
return null;
}
}
}
export class Widget implements IWidget{
constructor (public id: String, public name: String){
this.id = id;
this.name = name;
}
}
// Model types
class WidgetModel extends Widget implements IWidgetModel {
constructor(public id: String, public name: String){
super (id,name);
}
getWidget ():IWidget{
return this;
}
setWidget (_Widget:IWidget) : void {
this.id = _Widget.id;
this.name = _Widget.name;
}
getWidgetbyId (_id:String):IWidget{
if (_id === this.id){
return this;
} else {
return null;
}
}
}
// Mock data
var viewer:IUserModel = new UserModel('1','Anonymous');
var widgets:IWidget[] = ['What\'s-it', 'Who\'s-it', 'How\'s-it'].map((name:String, i:any) => {
let widget:IWidgetModel = new WidgetModel(name,`${i}`);
return widget;
});
export function getUser (_id:String):IUser {
return viewer.getUserbyId(_id);
}
export function getViewer ():IUser {
return viewer.getUser();
}
export function getWidget (_id:String):any {
widgets.forEach(
w => {
if (w.id === _id)
return w;
else
return null;
}
);
}
export function getWidgets (): IWidget[]{
return widgets;
}
tsconfig.json had
"module": "system",
Changed it to
"module": "umd",
and it worked.

Breeze createEntity Type not recognized

I'm trying to make my call to the server with BreezeJS but can't get it to work. It says tblMovie is not recognized. I can't find the problem :S
When I want to add a new movie it says so.
show.js
self.viewAddMovieModal = function () {
self.app.showModal(new self.addmovie()).then(function (result) {
if (result != undefined) {
var movie = dataservice.createMovie({
Title: result[0].title,
Director: result[0].director
});
if (movie.entityAspect.validateEntity()) {
self.movies.push(new movie(result[0].title, result[0].director));
dataservice.saveChanges();
} else {
alert("Error");
}
}
});
};
My dataservice.js layer
/// <reference path="../../Scripts/breeze.debug.js"/>
define(["require"], function (require) {
var Dataservice = (function () {
function Dataservice(service) {
this.serviceName = '';
this._isSaving = false;
this.serviceName = service;
this.Manager = new breeze.EntityManager(this.serviceName);
this.EntityQuery = new breeze.EntityQuery();
}
Dataservice.prototype.getAllMovies = function () {
this.EntityQuery = breeze.EntityQuery.from("AllMovies");
return this.Manager.executeQuery(this.EntityQuery);
};
Dataservice.prototype.createMovie = function (initialValues) {
return this.Manager.createEntity('tblMovies', initialValues); //THis is where it goes wrong :(
};
Dataservice.prototype.saveChanges = function (suppressLogIfNothingToSave) {
if (this.Manager.hasChanges()) {
if (this._isSaving) {
setTimeout(this.saveChanges, 50);
return;
}
this.Manager.saveChanges().then(this.saveSucceeded).fail(this.saveFailed).fin(this.saveFinished);
} else if (!suppressLogIfNothingToSave) {
}
};
Dataservice.prototype.saveSucceeded = function (saveResult) {
this._isSaving = false;
};
Dataservice.prototype.saveFailed = function (error) {
};
Dataservice.prototype.saveFinished = function () {
this._isSaving = false;
};
return Dataservice;
})();
return Dataservice;
})
I do have a model tblMovie
using System;
using System.ComponentModel.DataAnnotations;
namespace DurandalMovieApp.Models
{
public class tblMovie
{
[Key]
public int MovieID { get; set; }
public string Title { get; set; }
public string Director { get; set; }
}
}
Hope someone can help!
I think that the problem is that your entity is: tblMovie, not tblMovies.
Try replacing:
return this.Manager.createEntity('tblMovies', initialValues);
With:
return this.Manager.createEntity('tblMovie', initialValues);

Categories

Resources