Typescript how to declare a function that returns a lowest common denominator type? - typescript2.0

i want declare a function that returns a common type or its extended type
interface Common {
id: number;
}
interface AdditionalInformation extends Common {
myname: string;
}
Surely the function returns an object containing the id property
and wishing it could also return the myname property
I tried to declare the function like this:
export class Lib {
public static lowestCommonDenominator <T extends Common>(): Common {
const a: Common = { id: 1 };
return a;
}
public static firstCaseFunction(): Common {
const ok: Common = this.lowestCommonDenominator();
return ok;
}
public static secondCaseFunction(): AdditionalInformation {
// Property 'myname' is missing in type 'Common' but required in type 'AdditionalInformation'.ts(2741)
const ko: AdditionalInformation = this.lowestCommonDenominator();
return ko;
}
}
But when I assign the function to an extended type, I get the error:
Property 'myname' is missing in type 'Common' but required in type
'AdditionalInformation'.ts(2741)
Is it possible to implement what I want?

This code snippet removes the error
export class Lib {
public static lowestCommonDenominator <T extends Common>(): T {
const a: Common = { id: 1 };
return a as T;
}
public static firstCaseFunction(): Common {
const ok: Common = this.lowestCommonDenominator();
return ok;
}
public static secondCaseFunction(): AdditionalInformation {
const ko: AdditionalInformation = this.lowestCommonDenominator<AdditionalInformation>();
return ko;
}
}

Related

Access static mathod before using »super«

there is this class hierarchy:
class A {
constructor (obj) {
this.obj = obj
}
}
class B extends A {
static createObj () {
return {from: 'B'};
}
constructor () {
const obj = B.createObj();
super(obj);
}
}
I would like to extend this such that:
class C extends B {
static createObj () {
return { from: 'C' };
}
}
//such that:
console.log(new C().obj.from) // 'C'
BUT therefore I need to change const obj = B.createObj() to something like: const obj = Object.getPrototypeOf(this).constructor.createObj();, what is throwing this error:
ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor
So basically I would like to override a method that creates an object to be used within the super() call. Since this cannot be used before that, I chose to use a static method. Is there any way to reference the static method, without using this and without overriding the constructor as well?
If you really want your this.obj=obj to be done only in class A for some reason, then I would do:
class A {
constructor(obj) {
this.obj = obj
}
}
class B extends A {
static createObj() {
return { from: 'B' };
}
constructor(obj) {
if (!obj) obj = B.createObj();
super(obj);
}
}
class C extends B {
static createObj() {
return { from: 'C' };
}
constructor(obj) {
if (!obj) obj = C.createObj();
super(obj);
}
}
console.log(new C().obj.from)
Output:
"C"
But in my opinion the best OOP approach would be this:
class A {
constructor(obj) {
this.obj = obj
}
}
class B extends A {
static createObj() {
return { from: 'B' };
}
constructor(obj) {
super(obj);
this.obj = B.createObj();
}
}
class C extends B {
static createObj() {
return { from: 'C' };
}
constructor(obj) {
super(obj);
this.obj = C.createObj();
}
}
console.log(new C().obj.from)
Output:
"C"
The 2nd approach allows to satisfy the pattern "call super before doing anything else" that can prevent bugs.
It's up to you to chose which one better suits your needs, but both prints "C" without requiring Object.getPrototypeOf(this).constructor.createObj()

How to mock a top-level-function in kotlin with jmockit

Assuming the I have a function to be test below, declare at the file named "Utils.kt"
//Utils.kt
fun doSomething() = 1
Then we create a test class to test it
//UtilsTest.kt
#RunWith(JMockit::class)
class UtilsTest {
#Test
fun testDoSomething() {
object : Expectation() {
init {
doSomething()
result = 2
}
}
assertEquals(2, doSomething())
}
}
I want to mock doSomething, make it return 2, but it won't work, actual result is 1
Is there any workaround for this purpose?
A workaround mock it in Java side as you cannot reference the UtilsKt class from Kotlin files.
#RunWith(JMockit.class)
public final class UtilsFromJavaTest {
#Test
public final void testDoSomething(#Mocked #NotNull final UtilsKt mock) {
new Expectations() {
{
UtilsKt.doSomething();
this.result = 2;
}
};
Assert.assertEquals(2, UtilsKt.doSomething());
}
}
Thanks to #aristotll, we can simply extends the workaround to make it more easier to use.
first, declare a java class that return the UtilsKt class
//TopLevelFunctionClass.java
public class TopLevelFunctionClass {
public static Class<UtilsKt> getUtilsClass() {
return UtilsKt.class
}
}
then, mock this class in expectation using partial mock
//UtilsTest.kt
#RunWith(JMockit::class)
class UtilsTest {
#Test
fun testDoSomething() {
object : Expectation(TopLevelFunctionClass.getUtilsClass()) {
init {
doSomething()
result = 2
}
}
assertEquals(2, doSomething())
}
}

Typescript - Why should I rewrite all members to implement an interface?

I have an interface with some optional variables like:
interface A {
id: string;
name?: string;
email?: string;
...
}
What I want to do is that
class B implements A {
constructor(x: string, y: string, ...) {
this.id = x;
this.name = y;
...
}
getName(): string {
return this.name;
}
}
I don't want to rewrite all members that I will use and I need some members to stay optional. Each interface will be implemented with only one class, so if I rewrite all the members in class B than the interface A becomes useless.
You may ask "Why you need interface A anyway?". I need it because I am using it from some other project, and I have to extend and implement it with some functions.
Any solution or different idea about that implementation?
One option is to use Object.assign like so:
interface A {
id: string;
name?: string;
email?: string;
}
class B implements A {
id: string;
name: string;
email: string;
constructor(data: A) {
Object.assign(this, data);
}
getName(): string {
return this.name;
}
}
(code in playground)

Access members of outer class in TypeScript

Since TypeScript 1.6, we can easily create inner classes with class expressions. In other OOP-centric languages like Java, inner classes can access members of the outer class, even private ones.
This behavior is similar to concept of closures, where function could access variables from the scope in which it was defined.
Why I can't achieve this in TypeScript? Does specification of classes in ECMAScript 2015 plays role here?
Code that presents expected behavior:
class OuterClass {
private outerField = 1337;
public InnerClass = class {
public accessOuter() {
return this.outerField; // outerField not defined
}
}
}
var outer = new OuterClass();
var inner = new outer.InnerClass();
var win = inner.accessOuter();
It's easier to understand why you can't do that if you look at the compiled javascript of your code:
var OuterClass = (function () {
function OuterClass() {
this.outerField = 1337;
this.InnerClass = (function () {
function class_1() {
}
class_1.prototype.accessOuter = function () {
return this.outerField; // outerField not defined
};
return class_1;
}());
}
return OuterClass;
}());
As you can see, outerField is defined as a member of OuterClass like so:
this.outerField = 1337;
When you try to access it in your InnerClass you do:
return this.outerField;
But the this here is the instance of class_1 and not OuterClass so there's no outerField in this.
Also, you have no access from the inner class to the instance of the outer class.
The way this is solved in java is like so:
class OuterClass {
private int outerField = 1337;
public class InnerClass {
public int accessOuter() {
return OuterClass.this.outerField;
}
}
}
But there's no equivalent to OuterClass.this.outerField in typescript/javascript.
Look at typescript inner classes more like static inner classes in java, but here too you'll only be able to access public properties:
class OuterClass {
public static outerField = 1337; // has to be public
public InnerClass = class {
public accessOuter() {
return OuterClass.outerField;
}
}
}
You can pass an instance of the outer class to the inner class:
class OuterClass {
public outerField = 1337;
public InnerClass = class {
constructor(private parent: OuterClass) {}
public accessOuter() {
return this.parent.outerField;
}
}
}
But again, you'll need to have outerField public.
Edit
In case you want to achieve something that will simulate the needed behavior (that is, the inner class instance will have access to a private outer class members), then you can do something like this:
interface OuterClassProxy {
outerField: number;
}
interface IInnerClass {}
class OuterClass {
private outerField = 1337;
static InnerClass = class implements IInnerClass {
constructor(private parent: OuterClassProxy) {}
public accessOuter() {
return this.parent.outerField;
}
}
public createInnerClass(): IInnerClass {
let outerClassInstance = this;
return new OuterClass.InnerClass({
get outerField(): number {
return outerClassInstance.outerField;
},
set outerField(value: number) {
outerClassInstance.outerField = value;
}
});
}
}
It's quite a lot of work, but it will do it.
#Nitzan 's answer is great. I just wanted to add that I came up with this recently, maybe it helps:
class Outer {
constructor() {
this.val = 1337;
}
get Inner() {
let Outer = this;
return class {
accessVal() { return Outer.val; }
}
}
}
new (new Outer()).Inner().accessVal(); // 1337
Here is the correct way to do this in Typescript:
class OuterClass {
private outerField = 1337;
get InnerClass() {
const thatOuterField = this.outerField // <-- Notice this addition
return class {
public accessOuter() {
return thatOuterField; // outerField not defined
}
}
}
}
let outer = new OuterClass();
let inner = new outer.InnerClass();
let win = inner.accessOuter();
alert(win); // test works!
No need for anything convoluted.
This one did not work so bad for me:
function use<T>(value: T) {return new class {with<U>(f: (value: T) => U) {return f(value)}}}
class OuterClass {
private outerField = 1337;
InnerClass = use(this).with(outerThis => class {
accessOuter() {
return outerThis.outerField; // outerField not defined
}
}
}
const outer = new OuterClass()
const inner = new outer.InnerClass()
const win = inner.accessOuter()
console.log(win)

TypeScript + Class + createjs.EventDispatcher

I'm trying to use the createjs EventDispatcher as a way to dispatchEvents from a class. I'm extending my class using createjs.EventDispatcher and using the dispatchEvent to trigger the event.
I get the following error when this line isthis.dispatchEvent(createJSEvent); executed:
Uncaught InvalidStateError: Failed to execute 'dispatchEvent' on 'EventTarget': The event provided is null.
Simplified TypeScript code to demonstrate what I'd like to do:
export class deviceOrientation extends createjs.EventDispatcher {
constructor() {
super();
// wait 2 seconds and then fire testDispatch
setTimeout(this.testDispatch(), 2000);
}
testDispatch():void {
var createJSEvent:createjs.Event = new createjs.Event("change", true, true);
this.dispatchEvent(createJSEvent);
}
}
// This is the starting function
export function appExternalModuleTest(): void {
let _deviceOrientation: deviceOrientation;
_deviceOrientation = new deviceOrientation();
_deviceOrientation.addEventListener("change", () => this.changeOrientation());
//_deviceOrientation.on("progress", () => this.changeOrientation());
}
export function changeOrientationi(event: Event): void {
console.log('orienationHasChanged ');
}
I'm using easeljs-0.8.1.min.js
I'm not sure if this is possible with CreateJS. Is there a better approach?
Any help is greatly appreciated.
The problem looks strange, because I do almost the same in my project and don't have any problems.
In a nutshell, I have a d.ts file for createjs classes declaration and I use these declarations in my "normal" typescript classes.
For example:
d.ts:
declare module createjs
{
export class EventDispatcher
{
addEventListener(type: string, listener: any, useCapture?: boolean): void;
removeEventListener(type: string, listener: any, useCapture?: boolean): void;
removeAllEventListener(type?: string): void;
dispatchEvent(event: Event): boolean;
}
export class Event
{
public type: string;
public target: any;
public currentTarget: any;
constructor(type: string, bubbling?: boolean, cancelable?: boolean);
clone(): Event;
}
}
Normal class:
module flashist
{
export class TestEventDispatcher extends createjs.EventDispatcher
{
public constructor()
{
super();
}
public testDispatch(): void
{
var tempEvent: createjs.Event = new createjs.Event("test");
this.dispatchEvent(tempEvent);
}
}
}
And somewhere else in the code you should create an instance of the TestEventDispatcher class. Something like:
this.testDispatcher = new TestEventDispatcher();
this.testDispatcher.addEventListener("test", (event: createjs.Event) => alert("Test Event Listener"));
this.testDispatcher.testDispatch();
I've just tested the code and it works for me.
The only idea I have is to make sure that the easel.js file is loaded before your main app files.