During trying to enhance Angular's ComponetFixture I noticed that this can not be done because of no copying constructor for this class. (Or am I wrong?)
Let's suppose we have a class:
class A
{
constructor(public pub, private priv) { }
}
And I want to create class BetterA based on class A, so:
class BetterA extends A
{
constructor(a: A)
{
// super(a); <----- this can not be done, so maybe...
// super(a.pub, a.priv) // ...this could be better option, but...
}
myFunction(a: string) { return a; }
}
...second parameter is PRIVATE. I can not access it ;/
What can I do in that case?
I know that one of solutions is to use prototype like this:
A.prototype['myFunction'] = function(a: string) { return a; } // this must be done with function keyword, it's not working with ()=>{} !!! /there are problem with this pointer/
But then I have to write something weird like this:
console.log( classAobject['myFunction']("abc") );
Instead of
console.log( classAobject.myFunction("abc") );
or
I can do it by composition:
class B
{
public a: A; // or constructor(public a: A)
myFunction(a) { return a; }
}
But is seems not too elegant.
Is there any better solution?
Edit #1
I've just discovered that this syntax:
Class.prototype.NewFunction = function() { this.x.y.z = 123 }
is valid but it produces compiler errors, code works but we get:
'Property 'TextOf' does not exist on type 'Class'
and when you try to call it like this:
objectOfClass.NewFunction()
makes:
'Property 'NewFunction' does not exist on type 'Class'
BUT
It's gonna working only when we use function keyword. When we use lambda expression there will be same strange invisible problems with some functions.
I think composition is the way to go here. please remember that you are building a class and not a method which requires the new operator in order to instantiate your object. this may be what your looking for
class A{
tPub;
constructor(public pub, private priv) {
this.tPub=pub
}
}
class B extends A{
constructor(pub){
super(pub)
}
myFunc(){} //equiv to B.prototype.myFunc
}
export const myClass=new B();
//another file
import {myClass} from './file'
let m=myClass.myFunc();
unfortunately, by setting priv to private it will do exactly what it is told and make it a private object. you also could do without the constructor depending on what you would like to do with your class.
Related
I want to call a non-static method from static method. Both are in same class.
How can I achieve this ?
class Home extends React.Component {
constructor(props) {
super(props);
console.log("in constructor props =", this.props.mainData);
this.state = {
data: null,
isFetch: false,
clickEvent: false
}
this.allDataShow = this.allDataShow.bind(this);
this.upcomingShow = this.upcomingShow.bind(this);
}
allDataShow(){
allData(this.props.mainData);
}
upcomingShow(){
upcoming(this.props.mainData);
}
static changeData(option) {
console.log("I'm home changeData");
switch (option) {
case "All":
console.log("All");
allDataShow();
break;
case "Upcoming":
console.log("Upcoming");
console.log("this",this);
inst.prototype.upcomingShow();
break;
}
}
render(){...}
}
This is updated code in which I am calling changeData in another component, and in changeData I call non-static method. But it doesn't work.
The non-static method will be on the prototype, so reference My.prototype or this.prototype (this will refer to My inside the static method):
class My{
static my1(){
this.prototype.my2();
}
my2(){
console.log("my2 is executing");
}
}
My.my1();
That said, this is very weird - non-static methods are generally useful to refer to and use instance data. If the method uses instance data, it will need an instance to run sensibly. If the method doesn't use instance data, it probably shouldn't be a prototype method, but a static method or a standalone function.
You must instantiate a new "My" class and then call from there. You can either require the class as a parameter or make a new one in the method.
class My{
static my1(instance){
//something like this
instance.my2();
}
my2(){
console.log("my2 is executing");
}
}
var myInstance = new My();
My.my1(myInstance);
OR
class MyOther{
static my1(){
//something like this
var myInstance = new My();
myInstance.my2();
}
my2(){
console.log("my2 is executing");
}
}
MyOther.my1();
If i have classes like the following:
export class ClassA{
static Alpha: string;
static Beta: string[];
constructor(jsonData: any){
ClassA.Alpha = jsonData.alpha;
ClassA.Beta = new Array<string>();
for(let i=0; i<jsonData.betaList.length; i++){
ClassA.Beta.push(jsonData.betaList[i]);
}
//do whatever it takes that takes a really long time
}
}
export function foo(list: string[]){
//something
}
and when i write a code like the following:
let dat = //whatever to parse a certain json file
new ClassA(dat);
foo(ClassA.Beta);
I want to make sure that the initialization of ClassA.Beta is finished before foo() is called. is it possible? or does Typescript automatically handle such cases already?
You can be sure foo() will be executed after ClassA constructor is finished. Unless it uses any kind of async calls (Promises, setTimeout, etc.).
Having said that I think that current design is not the best one. Do you really want to initialize class static properties each time the constructor is called?
The better approach would be to have separate static initialization logic into Init() static method and call it in the proper place of your application:
export class ClassA{
static Alpha: string;
static Beta: string[];
public static Init(jsonData: any): void
{
ClassA.Alpha = jsonData.alpha;
ClassA.Beta = new Array<string>();
for(let i=0; i<jsonData.betaList.length; i++)
{
ClassA.Beta.push(jsonData.betaList[i]);
}
//do whatever it takes that takes a really long time
}
constructor()
{
//Initialize instance members here. Not static
}
}
export function foo(list: string[])
{
//something
}
let dat = {};//whatever to parse a certain json file
ClassA.Init(dat);
foo(ClassA.Beta);
This approach will allow you later to make Init() return Promise to make your code async if you will need to.
I'm very new to Haxe, and trying to make a simple tile-map creation program with OpenFL. However, I'm not sure how to make an array of classes (each individual tile types) I have made. It seems that a typedef is what I want, but I'm not sure how to incorporate this into an array so I can iterate through them.
Thanks in advance,
- RealFighter64
I assume the tile classes are all subclasses of a base class. In this case, just put them into an Array<Class<Base>> as follows:
class Base {
}
class A extends Base {
public function new():Void {}
}
class B extends Base {
public function new():Void {}
}
class C extends Base {
public function new():Void {}
}
class Test {
static function main() {
var classArray:Array<Class<Base>> = [A, B, C];
for (cls in classArray) {
var inst = Type.createInstance(cls, []);
}
}
}
If they do not have a common super class, use an Array<Dynamic> instead.
I have a list class that looks like this:
class List<T> {
private _array: Array<T>;
constructor() {
this._array = new Array<T>();
}
get count() { return this._array.length; }
public add = (state) => {
this._array.push(state);
}
...
}
And I would like to access the internal array from the class:
var something = list[0];
In c# I would do it something like this:
public T this[int index]
{
get
{
return _array[index];
}
private set {}
}
}
But I can't see anyway to accomplish this in TypeScript. Is there a way to add array accessors to my class so it looks more like a generic List ?
Thanks for the brainpower!
You can though the syntax is a bit weird. Note that since typescript gets compiled to js, only numbers and strings are valid keys:
interface IList<T> {
[index: number]: T
}
interface IMap<T> {
[index: string]: T
}
interface IMap<K, V> {
[index: K]: V // Error: Index signature parameter type must be either string or number
}
There's a trick to it though. You can't actually overload the operator, you can only tell the compiler that it exists. For instance if you have a generic object that you wish to use as a hashtable - declare it as Map<T> instead of any. The same goes for arrays.
The only possible way to actually put the operator in good use is to use an array or object as the underlying element, declare them as IList/IMap and then fiddle with their properties / prototype to add specific functionality. For example, to create an observable array see this answer
Given the following code:
class Type
{
static Property = 10;
}
class Type1 extends Type
{
static Property = 20;
}
class Type2 extends Type
{
static Property = 30;
}
I would like to make a function that can return an array of types that all inherit from the same base, that allows access to the "static side" of the class. For example:
function GetTypes(): typeof Type[]
{
return [Type1, Type2];
}
So now ideally I could go:
GetTypes(0).Property; // Equal to 20
However it doesn't seem like there is syntax for storing multiple typeof types in an array.
Is this correct?
Of course there is. Your code is correct minus the return type of the GetTypes function. (To be clear Steve's answer would solve your issue as well, this is just another approach without making use of interfaces).
Change the return type of the GetTypes function to:
function GetTypes(): Array<typeof Type>
{
return [Type1, Type2];
}
This should to the trick.
The correct way to do this would be to create an interface that describes the properties (or operations) supported by the type (that don't belong to an instance of the type):
interface Test {
x: number;
}
class MyType {
static x = 10;
}
class MyOtherType {
static x = 20;
}
var arr: Test[] = [MyType, MyOtherType];
alert(arr[0].x.toString());
alert(arr[1].x.toString());
No. It is currently only supported for single identifiers. I have made a feature request here: https://typescript.codeplex.com/workitem/1481
Nonetheless you can simply create a dummy interface to capture typeof Type and then use it in an Array i.e:
class Type
{
static Property = 10;
}
class Type1 extends Type
{
static Property = 20;
}
class Type2 extends Type
{
static Property = 30;
}
// Create a dummy interface to capture type
interface IType extends Type{}
// Use the dummy interface
function GetTypes(): IType[]
{
return [Type1, Type2];
}
GetTypes[0].Property; // Equal to 20
See it on the playground